title
stringlengths
1
100
titleSlug
stringlengths
3
77
Java
int64
0
1
Python3
int64
1
1
content
stringlengths
28
44.4k
voteCount
int64
0
3.67k
question_content
stringlengths
65
5k
question_hints
stringclasses
970 values
554: Solution with step by step explanation
brick-wall
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Create an empty dictionary called edge_counts.\n2. Loop through each row in the wall list:\na. Create a variable called edge_pos and set it to 0.\nb. Loop through each brick width in the current row up to the second to la...
5
There is a rectangular brick wall in front of you with `n` rows of bricks. The `ith` row has some number of bricks each of the same height (i.e., one unit) but they can be of different widths. The total width of each row is the same. Draw a vertical line from the top to the bottom and cross the least bricks. If your l...
null
Solution
brick-wall
1
1
```C++ []\nclass Solution {\npublic:\n int leastBricks(vector<vector<int>>& wall) {\n int len = 0, n = wall.size();\n for(int i = 0; i < wall[0].size(); ++i){\n len += wall[0][i];\n }\n unordered_map<int, int> freq{};\n for(int i = 0; i < n; ++i){\n int cur = ...
2
There is a rectangular brick wall in front of you with `n` rows of bricks. The `ith` row has some number of bricks each of the same height (i.e., one unit) but they can be of different widths. The total width of each row is the same. Draw a vertical line from the top to the bottom and cross the least bricks. If your l...
null
Python Elegant & Short | Prefix Sum
brick-wall
0
1
# Complexity\n- Time complexity: $$O(n * m)$$\n- Space complexity: $$O(m)$$\n\n# Code\n```\nclass Solution:\n def leastBricks(self, wall: List[List[int]]) -> int:\n n, m = len(wall), sum(wall[0])\n bricks = defaultdict(int)\n\n for row in wall:\n for acc in accumulate(row):\n ...
2
There is a rectangular brick wall in front of you with `n` rows of bricks. The `ith` row has some number of bricks each of the same height (i.e., one unit) but they can be of different widths. The total width of each row is the same. Draw a vertical line from the top to the bottom and cross the least bricks. If your l...
null
Concise Python code - please downvote
brick-wall
0
1
\n# Code\n```\nclass Solution:\n def leastBricks(self, wall: List[List[int]]) -> int:\n counter = collections.Counter(\n (\n val \n for row in wall\n for val in itertools.accumulate(row)\n )\n )\n data = counter.most_common(2)\n ...
0
There is a rectangular brick wall in front of you with `n` rows of bricks. The `ith` row has some number of bricks each of the same height (i.e., one unit) but they can be of different widths. The total width of each row is the same. Draw a vertical line from the top to the bottom and cross the least bricks. If your l...
null
Solution
next-greater-element-iii
1
1
```C++ []\nclass Solution {\npublic:\n int nextGreaterElement(int n) {\n auto digits = to_string(n);\n nextPermutation(begin(digits), end(digits));\n auto result = stoll(digits);\n return (result > numeric_limits<int>::max() || result <= n) ? -1 : result;\n }\nprivate:\n template<ty...
1
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 fi...
null
Python || MinHeap || Binary search || O(NlogN) complexity solution
next-greater-element-iii
0
1
Runtime: 30 ms, faster than **94.94%** of Python3 online submissions for Next Greater Element III.\nMemory Usage: 13.9 MB, less than 26.34% of Python3 online submissions for Next Greater Element III.\n\n* First, I want to tell you this is **NOT** the optimal solution. The optimal solution should have a time complexity ...
0
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 fi...
null
🔥[Python 3] Monotonic stack, with comments || beats 98%
next-greater-element-iii
0
1
```python3 []\nclass Solution:\n def nextGreaterElement(self, n: int) -> int:\n digits = list(map(int, str(n)))\n stack, L = [], len(digits)\n for i in reversed(range(L)):\n # because need to find smallest highest than n, need to work from the end\n # do, while not be found...
5
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 fi...
null
556: Solution with step by step explanation
next-greater-element-iii
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Convert the input number n into a list of digits.\n2. Traverse the list from right to left to find the first decreasing digit i-1.\n3. If there is no such digit, the input number is already the largest possible permutatio...
6
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 fi...
null
✅ 94.58% Split+Join & Two Pointers
reverse-words-in-a-string-iii
1
1
# Comprehensive Guide to Solving "Reverse Words in a String III"\n\n## Introduction & Problem Statement\n\nIn the "Reverse Words in a String III" problem, we are given a string `s`. The task is to reverse the order of characters in each word within a sentence while still preserving the whitespace and the initial word o...
49
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:** **Input:** s = "Let's take LeetCode contest" **Output:** "s'teL ekat edoCteeL tsetnoc" **Example 2:** **Input:** s = "God Ding" **Output:** "doG gniD" **Constr...
null
✅91.55%🔥Easy Solution🔥Reverse & Join
reverse-words-in-a-string-iii
1
1
# Problem\n##### The problem you\'re trying to solve is to reverse the order of characters in each word within a sentence while still preserving the original whitespace and the initial order of words.\n##### Here\'s an example to illustrate the problem:\n###### Input: "Let\'s take LeetCode contest"\n###### Output: "s\'...
124
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:** **Input:** s = "Let's take LeetCode contest" **Output:** "s'teL ekat edoCteeL tsetnoc" **Example 2:** **Input:** s = "God Ding" **Output:** "doG gniD" **Constr...
null
98% - BEGINNER FRIENDLY ONE TRAVERSAL APPROACH IN c++/JAVA/PYTHON3(TIME-O(N) SPACE-O(1))
reverse-words-in-a-string-iii
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe code provided is a C++ function named reverseWords that takes a string s as input and reverses the order of words in the string.\n\nHere\'s a breakdown of the code and its intuition:\n\n Initialization: Initialize variables i and j...
1
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:** **Input:** s = "Let's take LeetCode contest" **Output:** "s'teL ekat edoCteeL tsetnoc" **Example 2:** **Input:** s = "God Ding" **Output:** "doG gniD" **Constr...
null
NOOB CODE : Easy to Understand
reverse-words-in-a-string-iii
0
1
![1.png](https://assets.leetcode.com/users/images/28dbb134-d7d3-4783-9781-4929c9665e74_1696141822.823136.png)\n\n# Intuition\n1. Convert the sting to a list using split()\n2. Using for loop access each element of the list \n3. Reverse each element using basic string operation\n4. print the string \n# Approach\n1. `l = ...
2
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:** **Input:** s = "Let's take LeetCode contest" **Output:** "s'teL ekat edoCteeL tsetnoc" **Example 2:** **Input:** s = "God Ding" **Output:** "doG gniD" **Constr...
null
Easy to Understand || Two Pointer ||C++ || Python || Java
reverse-words-in-a-string-iii
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nExplanation of Approach:\n\nThe given code takes a string s as input and reverses each word within the string while maintaining the order of the words. It uses two pointers, start and end, to identify words in the string. He...
6
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:** **Input:** s = "Let's take LeetCode contest" **Output:** "s'teL ekat edoCteeL tsetnoc" **Example 2:** **Input:** s = "God Ding" **Output:** "doG gniD" **Constr...
null
Python 4 line code 96.68 % || 2 Approach
reverse-words-in-a-string-iii
0
1
**If you got help from this,... Plz Upvote .. it encourage me**\n\n# Code\n```\n<!-- 1st Approach Memory % is more -->\nclass Solution:\n def reverseWords(self, s: str) -> str:\n s = s.split(\' \')\n for i in range(len(s)):\n s[i] = s[i][::-1]\n return \' \'.join(s)\n\n\n# ===========...
5
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:** **Input:** s = "Let's take LeetCode contest" **Output:** "s'teL ekat edoCteeL tsetnoc" **Example 2:** **Input:** s = "God Ding" **Output:** "doG gniD" **Constr...
null
💯Faster✅💯 Lesser✅4 Methods🔥Using Split and Join🔥Using a Stack🔥Two-Pointers Approach🔥
reverse-words-in-a-string-iii
1
1
# \uD83D\uDE80 Hi, I\'m [Mohammed Raziullah Ansari](https://leetcode.com/Mohammed_Raziullah_Ansari/), and I\'m excited to share 4 ways to solve this question with detailed explanation of each approach:\n\n# Problem Explaination: \nThe "Reverse Words in a String III" problem is a common string manipulation problem often...
31
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:** **Input:** s = "Let's take LeetCode contest" **Output:** "s'teL ekat edoCteeL tsetnoc" **Example 2:** **Input:** s = "God Ding" **Output:** "doG gniD" **Constr...
null
Python 1-liner. Functional programming.
reverse-words-in-a-string-iii
0
1
# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```python\nclass Solution:\n def reverseWords(self, s: str) -> str:\n return \' \'.join(w[::-1] for w in s.split(\' \'))\n\n\n```
1
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:** **Input:** s = "Let's take LeetCode contest" **Output:** "s'teL ekat edoCteeL tsetnoc" **Example 2:** **Input:** s = "God Ding" **Output:** "doG gniD" **Constr...
null
Solution
logical-or-of-two-binary-grids-represented-as-quad-trees
1
1
```C++ []\nclass Solution {\npublic:\n Node* intersect(Node* quadTree1, Node* quadTree2) {\n if(quadTree1 -> isLeaf)\n {\n if(quadTree1 -> val == 1) return quadTree1;\n return quadTree2;\n }\n if(quadTree2 -> isLeaf)\n {\n if(quadTree2 -> val == 1) ...
1
A Binary Matrix is a matrix in which all the elements are either **0** or **1**. Given `quadTree1` and `quadTree2`. `quadTree1` represents a `n * n` binary matrix and `quadTree2` represents another `n * n` binary matrix. Return _a Quad-Tree_ representing the `n * n` binary matrix which is the result of **logical bitw...
null
Solution
logical-or-of-two-binary-grids-represented-as-quad-trees
1
1
```C++ []\nclass Solution {\npublic:\n Node* intersect(Node* quadTree1, Node* quadTree2) {\n if(quadTree1 -> isLeaf)\n {\n if(quadTree1 -> val == 1) return quadTree1;\n return quadTree2;\n }\n if(quadTree2 -> isLeaf)\n {\n if(quadTree2 -> val == 1) ...
1
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...
null
558: Time 99.4%, Solution with step by step explanation
logical-or-of-two-binary-grids-represented-as-quad-trees
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Check if either quadTree1 or quadTree2 is a leaf node. If quadTree1 is a leaf node, return quadTree1 if its value is True, else return quadTree2. If quadTree2 is a leaf node, return quadTree2 if its value is True, else re...
3
A Binary Matrix is a matrix in which all the elements are either **0** or **1**. Given `quadTree1` and `quadTree2`. `quadTree1` represents a `n * n` binary matrix and `quadTree2` represents another `n * n` binary matrix. Return _a Quad-Tree_ representing the `n * n` binary matrix which is the result of **logical bitw...
null
558: Time 99.4%, Solution with step by step explanation
logical-or-of-two-binary-grids-represented-as-quad-trees
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Check if either quadTree1 or quadTree2 is a leaf node. If quadTree1 is a leaf node, return quadTree1 if its value is True, else return quadTree2. If quadTree2 is a leaf node, return quadTree2 if its value is True, else re...
3
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...
null
558. Logical OR of Two Binary Grids Represented as Quad-Trees
logical-or-of-two-binary-grids-represented-as-quad-trees
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
A Binary Matrix is a matrix in which all the elements are either **0** or **1**. Given `quadTree1` and `quadTree2`. `quadTree1` represents a `n * n` binary matrix and `quadTree2` represents another `n * n` binary matrix. Return _a Quad-Tree_ representing the `n * n` binary matrix which is the result of **logical bitw...
null
558. Logical OR of Two Binary Grids Represented as Quad-Trees
logical-or-of-two-binary-grids-represented-as-quad-trees
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
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...
null
easy solution
logical-or-of-two-binary-grids-represented-as-quad-trees
1
1
\n\n# Code\n```java []\n/*\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 public Node() {}\n\n public Node(boolean _val,boolean _isLeaf,Node _...
0
A Binary Matrix is a matrix in which all the elements are either **0** or **1**. Given `quadTree1` and `quadTree2`. `quadTree1` represents a `n * n` binary matrix and `quadTree2` represents another `n * n` binary matrix. Return _a Quad-Tree_ representing the `n * n` binary matrix which is the result of **logical bitw...
null
easy solution
logical-or-of-two-binary-grids-represented-as-quad-trees
1
1
\n\n# Code\n```java []\n/*\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 public Node() {}\n\n public Node(boolean _val,boolean _isLeaf,Node _...
0
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...
null
Python solution for Quadtree Intersection Problem
logical-or-of-two-binary-grids-represented-as-quad-trees
0
1
# Intuition\nThe problem statement asks to find the intersection of two quadtrees. A quadtree is a tree data structure in which each internal node has exactly four children: top left, top right, bottom left, and bottom right. Each leaf node represents a square region and has a boolean value. The quadtree is a recursive...
0
A Binary Matrix is a matrix in which all the elements are either **0** or **1**. Given `quadTree1` and `quadTree2`. `quadTree1` represents a `n * n` binary matrix and `quadTree2` represents another `n * n` binary matrix. Return _a Quad-Tree_ representing the `n * n` binary matrix which is the result of **logical bitw...
null
Python solution for Quadtree Intersection Problem
logical-or-of-two-binary-grids-represented-as-quad-trees
0
1
# Intuition\nThe problem statement asks to find the intersection of two quadtrees. A quadtree is a tree data structure in which each internal node has exactly four children: top left, top right, bottom left, and bottom right. Each leaf node represents a square region and has a boolean value. The quadtree is a recursive...
0
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...
null
Python 3.10 match
logical-or-of-two-binary-grids-represented-as-quad-trees
0
1
# Approach\nRecursion\n\n# Code\n```\nclass Solution:\n def intersect(self, quadTree1: \'Node\', quadTree2: \'Node\') -> \'Node\':\n match (quadTree1,quadTree2):\n case (None,_)|(_,Node(isLeaf=1,val=1)):\n return quadTree2\n case (Node(isLeaf=1,val=1),_)|(_,None)|(Node(isL...
0
A Binary Matrix is a matrix in which all the elements are either **0** or **1**. Given `quadTree1` and `quadTree2`. `quadTree1` represents a `n * n` binary matrix and `quadTree2` represents another `n * n` binary matrix. Return _a Quad-Tree_ representing the `n * n` binary matrix which is the result of **logical bitw...
null
Python 3.10 match
logical-or-of-two-binary-grids-represented-as-quad-trees
0
1
# Approach\nRecursion\n\n# Code\n```\nclass Solution:\n def intersect(self, quadTree1: \'Node\', quadTree2: \'Node\') -> \'Node\':\n match (quadTree1,quadTree2):\n case (None,_)|(_,Node(isLeaf=1,val=1)):\n return quadTree2\n case (Node(isLeaf=1,val=1),_)|(_,None)|(Node(isL...
0
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...
null
[Python] Recursion; Explained
logical-or-of-two-binary-grids-represented-as-quad-trees
0
1
We can recursively traverse each branch of the two trees.\n\nSince we are solving bitwise OR of the two trees, there are some special handling when we build a new node based on the return nodes from the children:\n(1) if this node is a leaf node, we can directly return this node if its value is 1 or the other node is i...
0
A Binary Matrix is a matrix in which all the elements are either **0** or **1**. Given `quadTree1` and `quadTree2`. `quadTree1` represents a `n * n` binary matrix and `quadTree2` represents another `n * n` binary matrix. Return _a Quad-Tree_ representing the `n * n` binary matrix which is the result of **logical bitw...
null
[Python] Recursion; Explained
logical-or-of-two-binary-grids-represented-as-quad-trees
0
1
We can recursively traverse each branch of the two trees.\n\nSince we are solving bitwise OR of the two trees, there are some special handling when we build a new node based on the return nodes from the children:\n(1) if this node is a leaf node, we can directly return this node if its value is 1 or the other node is i...
0
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...
null
Python3 - Combine in place, then reconcile
logical-or-of-two-binary-grids-represented-as-quad-trees
0
1
# Intuition\nThis problem was more tedious than hard - child nodes should be in an array. Although, I did fail to simplify the output during the initial runthrough.\n\n# Code\n```\nclass Solution:\n def intersect(self, q1: \'Node\', q2: \'Node\') -> \'Node\':\n def rec(n1, n2):\n if n1.isLeaf and ...
0
A Binary Matrix is a matrix in which all the elements are either **0** or **1**. Given `quadTree1` and `quadTree2`. `quadTree1` represents a `n * n` binary matrix and `quadTree2` represents another `n * n` binary matrix. Return _a Quad-Tree_ representing the `n * n` binary matrix which is the result of **logical bitw...
null
Python3 - Combine in place, then reconcile
logical-or-of-two-binary-grids-represented-as-quad-trees
0
1
# Intuition\nThis problem was more tedious than hard - child nodes should be in an array. Although, I did fail to simplify the output during the initial runthrough.\n\n# Code\n```\nclass Solution:\n def intersect(self, q1: \'Node\', q2: \'Node\') -> \'Node\':\n def rec(n1, n2):\n if n1.isLeaf and ...
0
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...
null
Python3 🐍 concise solution beats 99%
logical-or-of-two-binary-grids-represented-as-quad-trees
0
1
# Code\n```\nclass Solution:\n def intersect(self, quadTree1: \'Node\', quadTree2: \'Node\') -> \'Node\':\n if quadTree1.isLeaf: return quadTree1 if quadTree1.val else quadTree2 # boundary condition \n if quadTree2.isLeaf: return quadTree2 if quadTree2.val else quadTree1 # boundary condition \n ...
0
A Binary Matrix is a matrix in which all the elements are either **0** or **1**. Given `quadTree1` and `quadTree2`. `quadTree1` represents a `n * n` binary matrix and `quadTree2` represents another `n * n` binary matrix. Return _a Quad-Tree_ representing the `n * n` binary matrix which is the result of **logical bitw...
null
Python3 🐍 concise solution beats 99%
logical-or-of-two-binary-grids-represented-as-quad-trees
0
1
# Code\n```\nclass Solution:\n def intersect(self, quadTree1: \'Node\', quadTree2: \'Node\') -> \'Node\':\n if quadTree1.isLeaf: return quadTree1 if quadTree1.val else quadTree2 # boundary condition \n if quadTree2.isLeaf: return quadTree2 if quadTree2.val else quadTree1 # boundary condition \n ...
0
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...
null
Python solution
logical-or-of-two-binary-grids-represented-as-quad-trees
0
1
# Approach\nThis problem is different from many other problems here. In reality we need to traverse both trees in parallel and construct the result tree. \nThe approach is defined as checking different cases:\n1. Two empty trees give an empty tree as the result (``None``)\n2. If one of the trees is empty - then result ...
0
A Binary Matrix is a matrix in which all the elements are either **0** or **1**. Given `quadTree1` and `quadTree2`. `quadTree1` represents a `n * n` binary matrix and `quadTree2` represents another `n * n` binary matrix. Return _a Quad-Tree_ representing the `n * n` binary matrix which is the result of **logical bitw...
null
Python solution
logical-or-of-two-binary-grids-represented-as-quad-trees
0
1
# Approach\nThis problem is different from many other problems here. In reality we need to traverse both trees in parallel and construct the result tree. \nThe approach is defined as checking different cases:\n1. Two empty trees give an empty tree as the result (``None``)\n2. If one of the trees is empty - then result ...
0
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...
null
[Python3] 9-line recursive (64ms 93.33%)
logical-or-of-two-binary-grids-represented-as-quad-trees
0
1
\n```\nclass Solution:\n def intersect(self, quadTree1: \'Node\', quadTree2: \'Node\') -> \'Node\':\n if quadTree1.isLeaf: return quadTree1 if quadTree1.val else quadTree2 # boundary condition \n if quadTree2.isLeaf: return quadTree2 if quadTree2.val else quadTree1 # boundary condition \n tl = s...
2
A Binary Matrix is a matrix in which all the elements are either **0** or **1**. Given `quadTree1` and `quadTree2`. `quadTree1` represents a `n * n` binary matrix and `quadTree2` represents another `n * n` binary matrix. Return _a Quad-Tree_ representing the `n * n` binary matrix which is the result of **logical bitw...
null
[Python3] 9-line recursive (64ms 93.33%)
logical-or-of-two-binary-grids-represented-as-quad-trees
0
1
\n```\nclass Solution:\n def intersect(self, quadTree1: \'Node\', quadTree2: \'Node\') -> \'Node\':\n if quadTree1.isLeaf: return quadTree1 if quadTree1.val else quadTree2 # boundary condition \n if quadTree2.isLeaf: return quadTree2 if quadTree2.val else quadTree1 # boundary condition \n tl = s...
2
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...
null
[Python || O(N)]
maximum-depth-of-n-ary-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n- O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- O(N)\n<!-- Add your space complexity here, ...
1
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...
null
[Python || O(N)]
maximum-depth-of-n-ary-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n- O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- O(N)\n<!-- Add your space complexity here, ...
1
You are given an integer array `stations` that represents the positions of the gas stations on the **x-axis**. You are also given an integer `k`. You should add `k` new gas stations. You can add the stations anywhere on the **x-axis**, and not necessarily on an integer position. Let `penalty()` be the maximum distanc...
null
6 lines awesome code
maximum-depth-of-n-ary-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
3
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...
null
6 lines awesome code
maximum-depth-of-n-ary-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
3
You are given an integer array `stations` that represents the positions of the gas stations on the **x-axis**. You are also given an integer `k`. You should add `k` new gas stations. You can add the stations anywhere on the **x-axis**, and not necessarily on an integer position. Let `penalty()` be the maximum distanc...
null
559: Time 95.76%, Solution with step by step explanation
maximum-depth-of-n-ary-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Check if the root node is None. If it is, return 0 as the maximum depth since there are no nodes in the tree.\n2. Create a variable called max_depth and set it to 0. This variable will keep track of the maximum depth of t...
6
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...
null
559: Time 95.76%, Solution with step by step explanation
maximum-depth-of-n-ary-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Check if the root node is None. If it is, return 0 as the maximum depth since there are no nodes in the tree.\n2. Create a variable called max_depth and set it to 0. This variable will keep track of the maximum depth of t...
6
You are given an integer array `stations` that represents the positions of the gas stations on the **x-axis**. You are also given an integer `k`. You should add `k` new gas stations. You can add the stations anywhere on the **x-axis**, and not necessarily on an integer position. Let `penalty()` be the maximum distanc...
null
[ Python ] Easy Solution | Faster than 94% submits
maximum-depth-of-n-ary-tree
0
1
```\nclass 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 \n```
6
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...
null
[ Python ] Easy Solution | Faster than 94% submits
maximum-depth-of-n-ary-tree
0
1
```\nclass 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 \n```
6
You are given an integer array `stations` that represents the positions of the gas stations on the **x-axis**. You are also given an integer `k`. You should add `k` new gas stations. You can add the stations anywhere on the **x-axis**, and not necessarily on an integer position. Let `penalty()` be the maximum distanc...
null
PYTHON_(Simple BFS || Beats(TC : 99%))
maximum-depth-of-n-ary-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(V+E)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g....
1
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...
null
PYTHON_(Simple BFS || Beats(TC : 99%))
maximum-depth-of-n-ary-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(V+E)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g....
1
You are given an integer array `stations` that represents the positions of the gas stations on the **x-axis**. You are also given an integer `k`. You should add `k` new gas stations. You can add the stations anywhere on the **x-axis**, and not necessarily on an integer position. Let `penalty()` be the maximum distanc...
null
Python BFS Iterative Beats 92%
maximum-depth-of-n-ary-tree
0
1
```\nclass Solution:\n def maxDepth(self, root: \'Node\') -> int:\n if not root:\n return 0\n \n nodes = deque()\n nodes.append((root, 1))\n maxx = 0\n while nodes:\n cur, val = nodes.popleft()\n maxx = val\n if cur.children:\n ...
10
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...
null
Python BFS Iterative Beats 92%
maximum-depth-of-n-ary-tree
0
1
```\nclass Solution:\n def maxDepth(self, root: \'Node\') -> int:\n if not root:\n return 0\n \n nodes = deque()\n nodes.append((root, 1))\n maxx = 0\n while nodes:\n cur, val = nodes.popleft()\n maxx = val\n if cur.children:\n ...
10
You are given an integer array `stations` that represents the positions of the gas stations on the **x-axis**. You are also given an integer `k`. You should add `k` new gas stations. You can add the stations anywhere on the **x-axis**, and not necessarily on an integer position. Let `penalty()` be the maximum distanc...
null
[ Python ] ✅✅ Simple Python Solution Using PrefixSum and Dictionary 🔥✌
subarray-sum-equals-k
0
1
\n# If You like the Solution, Don\'t Forget To UpVote Me, Please UpVote! \uD83D\uDD3C\uD83D\uDE4F\n\tclass Solution:\n\t\tdef subarraySum(self, nums: List[int], k: int) -> int:\n\n\t\t\tresult = 0 \n\t\t\tprefix_sum = 0\n\t\t\td = {0 : 1}\n\n\t\t\tfor num in nums:\n\t\t\t\n\t\t\t\tprefix_sum = prefix_sum + num\n\n\t\t\...
304
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:** **Input:** nums = \[1,1,1\], k = 2 **Output:** 2 **Example 2:** **Input:** nums = \[1,2,3\], k = 3 **Ou...
Will Brute force work here? Try to optimize it. Can we optimize it by using some extra space? What about storing sum frequencies in a hash table? Will it be useful? sum(i,j)=sum(0,j)-sum(0,i), where sum(i,j) represents the sum of all the elements from index i to j-1. Can we use this property to optimize it.
[ Python ] ✅✅ Simple Python Solution Using PrefixSum and Dictionary 🔥✌
subarray-sum-equals-k
0
1
\n# If You like the Solution, Don\'t Forget To UpVote Me, Please UpVote! \uD83D\uDD3C\uD83D\uDE4F\n\tclass Solution:\n\t\tdef subarraySum(self, nums: List[int], k: int) -> int:\n\n\t\t\tresult = 0 \n\t\t\tprefix_sum = 0\n\t\t\td = {0 : 1}\n\n\t\t\tfor num in nums:\n\t\t\t\n\t\t\t\tprefix_sum = prefix_sum + num\n\n\t\t\...
304
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:** **Input:** nums = \[1,1,1\], k = 2 **Output:** 2 **Example 2:** **Input:** nums = \[1,2,3\], k = 3 **Ou...
Will Brute force work here? Try to optimize it. Can we optimize it by using some extra space? What about storing sum frequencies in a hash table? Will it be useful? sum(i,j)=sum(0,j)-sum(0,i), where sum(i,j) represents the sum of all the elements from index i to j-1. Can we use this property to optimize it.
Python 3 Solution for Problem no. 560.
subarray-sum-equals-k
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nUsing prefix sum and dictionary.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass...
1
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:** **Input:** nums = \[1,1,1\], k = 2 **Output:** 2 **Example 2:** **Input:** nums = \[1,2,3\], k = 3 **Ou...
Will Brute force work here? Try to optimize it. Can we optimize it by using some extra space? What about storing sum frequencies in a hash table? Will it be useful? sum(i,j)=sum(0,j)-sum(0,i), where sum(i,j) represents the sum of all the elements from index i to j-1. Can we use this property to optimize it.
Python 3 Solution for Problem no. 560.
subarray-sum-equals-k
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nUsing prefix sum and dictionary.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass...
1
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:** **Input:** nums = \[1,1,1\], k = 2 **Output:** 2 **Example 2:** **Input:** nums = \[1,2,3\], k = 3 **Ou...
Will Brute force work here? Try to optimize it. Can we optimize it by using some extra space? What about storing sum frequencies in a hash table? Will it be useful? sum(i,j)=sum(0,j)-sum(0,i), where sum(i,j) represents the sum of all the elements from index i to j-1. Can we use this property to optimize it.
✅☑[C++/C/Java/Python/JavaScript] || Easiest Approach So Far || Beats 100% || EXPLAINED🔥
subarray-sum-equals-k
1
1
# *PLEASE UPVOTE IF IT HELPED*\n\n---\n\n\n# Approaches\n***(Also explained in the code)***\n1. **Initialize variables:**\n\n - `n` as the length of the input `nums` array.\n - `prefix` array to store prefix sums, where `prefix[i]` represents the sum of all elements from index 0 to `i` in `nums`.\n - Initializ...
8
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:** **Input:** nums = \[1,1,1\], k = 2 **Output:** 2 **Example 2:** **Input:** nums = \[1,2,3\], k = 3 **Ou...
Will Brute force work here? Try to optimize it. Can we optimize it by using some extra space? What about storing sum frequencies in a hash table? Will it be useful? sum(i,j)=sum(0,j)-sum(0,i), where sum(i,j) represents the sum of all the elements from index i to j-1. Can we use this property to optimize it.
✅☑[C++/C/Java/Python/JavaScript] || Easiest Approach So Far || Beats 100% || EXPLAINED🔥
subarray-sum-equals-k
1
1
# *PLEASE UPVOTE IF IT HELPED*\n\n---\n\n\n# Approaches\n***(Also explained in the code)***\n1. **Initialize variables:**\n\n - `n` as the length of the input `nums` array.\n - `prefix` array to store prefix sums, where `prefix[i]` represents the sum of all elements from index 0 to `i` in `nums`.\n - Initializ...
8
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:** **Input:** nums = \[1,1,1\], k = 2 **Output:** 2 **Example 2:** **Input:** nums = \[1,2,3\], k = 3 **Ou...
Will Brute force work here? Try to optimize it. Can we optimize it by using some extra space? What about storing sum frequencies in a hash table? Will it be useful? sum(i,j)=sum(0,j)-sum(0,i), where sum(i,j) represents the sum of all the elements from index i to j-1. Can we use this property to optimize it.
Easy python solution
subarray-sum-equals-k
0
1
# Code\n```\nclass Solution:\n def subarraySum(self, nums: List[int], k: int) -> int:\n cnt=0\n dic={}\n for i in accumulate(nums):\n if i-k in dic:\n cnt+=dic[i-k]\n if i==k:cnt+=1\n if i in dic:dic[i]+=1\n else:dic[i]=1\n return...
1
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:** **Input:** nums = \[1,1,1\], k = 2 **Output:** 2 **Example 2:** **Input:** nums = \[1,2,3\], k = 3 **Ou...
Will Brute force work here? Try to optimize it. Can we optimize it by using some extra space? What about storing sum frequencies in a hash table? Will it be useful? sum(i,j)=sum(0,j)-sum(0,i), where sum(i,j) represents the sum of all the elements from index i to j-1. Can we use this property to optimize it.
Easy python solution
subarray-sum-equals-k
0
1
# Code\n```\nclass Solution:\n def subarraySum(self, nums: List[int], k: int) -> int:\n cnt=0\n dic={}\n for i in accumulate(nums):\n if i-k in dic:\n cnt+=dic[i-k]\n if i==k:cnt+=1\n if i in dic:dic[i]+=1\n else:dic[i]=1\n return...
1
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:** **Input:** nums = \[1,1,1\], k = 2 **Output:** 2 **Example 2:** **Input:** nums = \[1,2,3\], k = 3 **Ou...
Will Brute force work here? Try to optimize it. Can we optimize it by using some extra space? What about storing sum frequencies in a hash table? Will it be useful? sum(i,j)=sum(0,j)-sum(0,i), where sum(i,j) represents the sum of all the elements from index i to j-1. Can we use this property to optimize it.
Simple Python solution with linear time complexity!! 🔥🔥
subarray-sum-equals-k
0
1
# Code\n```\nclass Solution:\n def subarraySum(self, nums: List[int], k: int) -> int:\n res=0\n curSum=0\n prefixSums={0:1}\n\n for n in nums:\n curSum+=n\n diff=curSum-k\n res+=prefixSums.get(diff,0)\n prefixSums[curSum]=1+prefixSums.get(curSum...
2
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:** **Input:** nums = \[1,1,1\], k = 2 **Output:** 2 **Example 2:** **Input:** nums = \[1,2,3\], k = 3 **Ou...
Will Brute force work here? Try to optimize it. Can we optimize it by using some extra space? What about storing sum frequencies in a hash table? Will it be useful? sum(i,j)=sum(0,j)-sum(0,i), where sum(i,j) represents the sum of all the elements from index i to j-1. Can we use this property to optimize it.
Simple Python solution with linear time complexity!! 🔥🔥
subarray-sum-equals-k
0
1
# Code\n```\nclass Solution:\n def subarraySum(self, nums: List[int], k: int) -> int:\n res=0\n curSum=0\n prefixSums={0:1}\n\n for n in nums:\n curSum+=n\n diff=curSum-k\n res+=prefixSums.get(diff,0)\n prefixSums[curSum]=1+prefixSums.get(curSum...
2
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:** **Input:** nums = \[1,1,1\], k = 2 **Output:** 2 **Example 2:** **Input:** nums = \[1,2,3\], k = 3 **Ou...
Will Brute force work here? Try to optimize it. Can we optimize it by using some extra space? What about storing sum frequencies in a hash table? Will it be useful? sum(i,j)=sum(0,j)-sum(0,i), where sum(i,j) represents the sum of all the elements from index i to j-1. Can we use this property to optimize it.
Solution with lil explanation
array-partition
0
1
\n```\nnums = [1,4,3,2]\n\nExplanation:\n------------ \nAll 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...
1
Given an integer array `nums` of `2n` integers, group these integers into `n` pairs `(a1, b1), (a2, b2), ..., (an, bn)` such that the sum of `min(ai, bi)` for all `i` is **maximized**. Return _the maximized sum_. **Example 1:** **Input:** nums = \[1,4,3,2\] **Output:** 4 **Explanation:** All possible pairings (ignori...
Obviously, brute force won't help here. Think of something else, take some example like 1,2,3,4. How will you make pairs to get the result? There must be some pattern. Did you observe that- Minimum element gets add into the result in sacrifice of maximum element. Still won't able to find pairs? Sort the array and try t...
2 One-liner 1 detailed Python3 Beat 97.4% 259ms
array-partition
0
1
\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n logn)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def arrayPairSum(self, nums: List[int]) -> int:\n #1st Approach\n nums.sort()\n ...
2
Given an integer array `nums` of `2n` integers, group these integers into `n` pairs `(a1, b1), (a2, b2), ..., (an, bn)` such that the sum of `min(ai, bi)` for all `i` is **maximized**. Return _the maximized sum_. **Example 1:** **Input:** nums = \[1,4,3,2\] **Output:** 4 **Explanation:** All possible pairings (ignori...
Obviously, brute force won't help here. Think of something else, take some example like 1,2,3,4. How will you make pairs to get the result? There must be some pattern. Did you observe that- Minimum element gets add into the result in sacrifice of maximum element. Still won't able to find pairs? Sort the array and try t...
Algorithm and solution in python3
array-partition
0
1
The question states that we have to find the maximum sum obtained by taking minimum from **n** pairs. A pair can be formed from the elements of the list.\n\nHow to solve this:\n- **Sort** the list\n- **make a pair** starting from index 0\n- take **minimum** from each pair\n- **add** all the minimum obtained from the pa...
59
Given an integer array `nums` of `2n` integers, group these integers into `n` pairs `(a1, b1), (a2, b2), ..., (an, bn)` such that the sum of `min(ai, bi)` for all `i` is **maximized**. Return _the maximized sum_. **Example 1:** **Input:** nums = \[1,4,3,2\] **Output:** 4 **Explanation:** All possible pairings (ignori...
Obviously, brute force won't help here. Think of something else, take some example like 1,2,3,4. How will you make pairs to get the result? There must be some pattern. Did you observe that- Minimum element gets add into the result in sacrifice of maximum element. Still won't able to find pairs? Sort the array and try t...
563: Time 93.99%, Solution with step by step explanation
binary-tree-tilt
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Set the "total_tilt" attribute to 0 as we will be incrementally adding to this as we calculate the tilt of each node.\n2. Define a helper function called "calculate_tilt" that takes in a node and returns an integer repres...
6
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**...
Don't think too much, this is an easy problem. Take some small tree as an example. Can a parent node use the values of its child nodes? How will you implement it? May be recursion and tree traversal can help you in implementing. What about postorder traversal, using values of left and right childs?
Solution
binary-tree-tilt
1
1
```C++ []\nclass Solution {\npublic:\nint sum=0;\n int findTilt(TreeNode* root) {\n fun(root);\n return sum;\n }\n int fun(TreeNode* root){\n if(root==NULL){\n return 0;\n }\n int left=fun(root->left);\n int right=fun(root->right);\n\n sum=sum+ab...
3
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**...
Don't think too much, this is an easy problem. Take some small tree as an example. Can a parent node use the values of its child nodes? How will you implement it? May be recursion and tree traversal can help you in implementing. What about postorder traversal, using values of left and right childs?
Recursive solution Python
binary-tree-tilt
0
1
Time complexity: O(N) because you need to check for every element once\nSpace complexity: O(N) because of the recursion stack\n\n```\nclass Solution:\n def findTilt(self, root: Optional[TreeNode]) -> int:\n def rec(node):\n nonlocal res\n if not node:\n return 0\n ...
3
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**...
Don't think too much, this is an easy problem. Take some small tree as an example. Can a parent node use the values of its child nodes? How will you implement it? May be recursion and tree traversal can help you in implementing. What about postorder traversal, using values of left and right childs?
---Explained ---Easy code in python3 with constant Time ----
find-the-closest-palindrome
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nYou have to check 7 tests.Check minimum absolute difference and return the element with minimum difference\n- For example we have 100000\n1. (10^(len))+1 , i.e(100...
12
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:** **Input:** n = "123 " **Output:** "121 " **Examp...
Will brute force work for this problem? Think of something else. Take some examples like 1234, 999,1000, etc and check their closest palindromes. How many different cases are possible? Do we have to consider only left half or right half of the string or both? Try to find the closest palindrome of these numbers- 12932, ...
Python 3 || 8 lines, w/ comments || T/M: 86% / 83%
find-the-closest-palindrome
0
1
```\nclass Solution:\n def nearestPalindromic(self, n: str) -> str:\n\n k = len(n)\n cands = {str(c:=pow(10,k)+1), str((c-1)//10-1)} # The two edge-case candidates\n # (e.g: "10001" and "999" \n ...
5
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:** **Input:** n = "123 " **Output:** "121 " **Examp...
Will brute force work for this problem? Think of something else. Take some examples like 1234, 999,1000, etc and check their closest palindromes. How many different cases are possible? Do we have to consider only left half or right half of the string or both? Try to find the closest palindrome of these numbers- 12932, ...
Beats 99%.A very unique approach.O(n) time complexity
find-the-closest-palindrome
0
1
# Intuition\nDone with checking 7 conditions\n# Approach\n1.first we\'ll check 10**n+1,10**n-1,10**(n-1)-1,10**(n-1)+1.4 are done\n2.Then,we\'ll make a palindrome of half of given n+inverse of n e.g. "123" = "121".5 is done\n3.now we\'ll check last two conditions half of given (n+1) + inverse of (n+1) and (n-1) + inver...
3
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:** **Input:** n = "123 " **Output:** "121 " **Examp...
Will brute force work for this problem? Think of something else. Take some examples like 1234, 999,1000, etc and check their closest palindromes. How many different cases are possible? Do we have to consider only left half or right half of the string or both? Try to find the closest palindrome of these numbers- 12932, ...
Only 5 Cases to Consider: Concise implementation in Python with Full Explanation
find-the-closest-palindrome
0
1
The implementation can be annoying for handling the carry and the borrow at the boundary. To make easy, we reduce all the cases into 5 possibilities only. Taking the number 1234 as an example, we find the closest one from the following candidates: \n\n1. 1221 # Case 1: the palindrome with the same first-half to [12]3...
7
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:** **Input:** n = "123 " **Output:** "121 " **Examp...
Will brute force work for this problem? Think of something else. Take some examples like 1234, 999,1000, etc and check their closest palindromes. How many different cases are possible? Do we have to consider only left half or right half of the string or both? Try to find the closest palindrome of these numbers- 12932, ...
[Python] 3 lines with comments || Case by Case
find-the-closest-palindrome
0
1
It took couple of WA before getting AC, edge cases are really annoying... \n\n# Code\n```\nclass Solution:\n """\n what are the possible candidates for answer? \n Main case: \n 1. reflection 12345: 12321 (+1)\n edge cases:\n 2. 4 digits: 999 1001 9999 10001 (+4)\n 3. 1283? c...
1
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:** **Input:** n = "123 " **Output:** "121 " **Examp...
Will brute force work for this problem? Think of something else. Take some examples like 1234, 999,1000, etc and check their closest palindromes. How many different cases are possible? Do we have to consider only left half or right half of the string or both? Try to find the closest palindrome of these numbers- 12932, ...
Solution
find-the-closest-palindrome
1
1
```C++ []\nclass Solution {\npublic:\n string nearestPalindromic(string n) {\n if(n.length()==1)\n return to_string(stoi(n)-1);\n \n int d = n.length();\n vector<long> candidates;\n candidates.push_back(pow(10,d-1)-1);\n candidates.push_back(pow(10,d)+1);\n\n ...
2
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:** **Input:** n = "123 " **Output:** "121 " **Examp...
Will brute force work for this problem? Think of something else. Take some examples like 1234, 999,1000, etc and check their closest palindromes. How many different cases are possible? Do we have to consider only left half or right half of the string or both? Try to find the closest palindrome of these numbers- 12932, ...
565: Time 90.23%, Solution with step by step explanation
array-nesting
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nInitialize a boolean visited list of size n, where visited[i] indicates if nums[i] has been visited or not.\nInitialize a variable max_length to zero, which will be used to store the maximum length of any set.\nIterate over ...
2
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: * The first element in `s[k]` starts with the selection of the element `num...
null
CLEAN & SHORT PYTHON, O(N) TIME, O(N) SPACE
array-nesting
0
1
* If the number is not present in the global set, then calculate the respective set for that number,\n* Else just continue because that number will yeild an already visited set ( and that will not make any difference to the result).\n```\nclass Solution:\n def arrayNesting(self, nums: List[int]) -> int:\n res...
7
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: * The first element in `s[k]` starts with the selection of the element `num...
null
Solution
array-nesting
1
1
```C++ []\nclass Solution {\npublic:\n int arrayNesting(vector<int>& nums) {\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n\n int maxLen = 1;\n for (int i = 0; i < nums.size(); ++i) {\n if (nums[i] == i) continue;\n int currLen = 1;\n while (nums[i...
2
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: * The first element in `s[k]` starts with the selection of the element `num...
null
Python3 | Strongly Connected Components
array-nesting
0
1
# Intuition\nThe array $\\mathrm{nums}$ can be modelled as a graph where there\'s a *directed edge* from $i$ to $\\mathrm{nums}[i]$, for $0 \\le i < n$. Once the situation is modelled as a graph, all that is left to do is finding the strongly connected components and returning the size of the largest one.\n\n# Approach...
0
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: * The first element in `s[k]` starts with the selection of the element `num...
null
Python || O(1) Space Solution
array-nesting
0
1
```\nVISITED = -1\n\n\nclass Solution:\n def arrayNesting(self, A: list[int]) -> int:\n # return self.simple_solution(A)\n return self.space_efficient_solution(A)\n\n @staticmethod\n def simple_solution(A: list[int]) -> int:\n n = len(A)\n\n is_visited = [False] * n\n\n def d...
0
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: * The first element in `s[k]` starts with the selection of the element `num...
null
[Python] Intuitive + Direct for Beginners with Illustrations
reshape-the-matrix
0
1
Given a matrix `mat` of 3 rows * 4 columns, \nwe want reshape it into 2 rows (`r = 2`) * 6 columns(`c = 6`): \n```\n[[0, 1, 2, 3],\n [4, 5, 6, 7], -> [[0, 1, 2, 3, 4, 5],\n [8, 9, 10, 11]] [6, 7, 8, 9, 10, 11]]\n```\n**Step 1:** Flatten t...
130
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. ...
Do you know how 2d matrix is stored in 1d memory? Try to map 2-dimensions into one. M[i][j]=M[n*i+j] , where n is the number of cols. This is the one way of converting 2-d indices into one 1-d index. Now, how will you convert 1-d index into 2-d indices? Try to use division and modulus to convert 1-d index into 2-d...
[Python] Intuitive + Direct for Beginners with Illustrations
reshape-the-matrix
0
1
Given a matrix `mat` of 3 rows * 4 columns, \nwe want reshape it into 2 rows (`r = 2`) * 6 columns(`c = 6`): \n```\n[[0, 1, 2, 3],\n [4, 5, 6, 7], -> [[0, 1, 2, 3, 4, 5],\n [8, 9, 10, 11]] [6, 7, 8, 9, 10, 11]]\n```\n**Step 1:** Flatten t...
130
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. ...
Do you know how 2d matrix is stored in 1d memory? Try to map 2-dimensions into one. M[i][j]=M[n*i+j] , where n is the number of cols. This is the one way of converting 2-d indices into one 1-d index. Now, how will you convert 1-d index into 2-d indices? Try to use division and modulus to convert 1-d index into 2-d i...
easy solution || Reshape the Matrix
reshape-the-matrix
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
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. ...
Do you know how 2d matrix is stored in 1d memory? Try to map 2-dimensions into one. M[i][j]=M[n*i+j] , where n is the number of cols. This is the one way of converting 2-d indices into one 1-d index. Now, how will you convert 1-d index into 2-d indices? Try to use division and modulus to convert 1-d index into 2-d...
easy solution || Reshape the Matrix
reshape-the-matrix
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
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. ...
Do you know how 2d matrix is stored in 1d memory? Try to map 2-dimensions into one. M[i][j]=M[n*i+j] , where n is the number of cols. This is the one way of converting 2-d indices into one 1-d index. Now, how will you convert 1-d index into 2-d indices? Try to use division and modulus to convert 1-d index into 2-d i...
[Python] - Clean & Simple - O(m*n) Solution
reshape-the-matrix
0
1
# Complexity\n- Time complexity: $$O(m*n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(m*n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:\n m =...
6
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. ...
Do you know how 2d matrix is stored in 1d memory? Try to map 2-dimensions into one. M[i][j]=M[n*i+j] , where n is the number of cols. This is the one way of converting 2-d indices into one 1-d index. Now, how will you convert 1-d index into 2-d indices? Try to use division and modulus to convert 1-d index into 2-d...
[Python] - Clean & Simple - O(m*n) Solution
reshape-the-matrix
0
1
# Complexity\n- Time complexity: $$O(m*n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(m*n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:\n m =...
6
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. ...
Do you know how 2d matrix is stored in 1d memory? Try to map 2-dimensions into one. M[i][j]=M[n*i+j] , where n is the number of cols. This is the one way of converting 2-d indices into one 1-d index. Now, how will you convert 1-d index into 2-d indices? Try to use division and modulus to convert 1-d index into 2-d i...
566: Solution with step by step explanation
reshape-the-matrix
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. First, check if it is possible to reshape the matrix by comparing the product of the number of rows and columns of the original matrix with the product of the number of rows and columns of the desired reshaped matrix. If ...
5
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. ...
Do you know how 2d matrix is stored in 1d memory? Try to map 2-dimensions into one. M[i][j]=M[n*i+j] , where n is the number of cols. This is the one way of converting 2-d indices into one 1-d index. Now, how will you convert 1-d index into 2-d indices? Try to use division and modulus to convert 1-d index into 2-d...
566: Solution with step by step explanation
reshape-the-matrix
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. First, check if it is possible to reshape the matrix by comparing the product of the number of rows and columns of the original matrix with the product of the number of rows and columns of the desired reshaped matrix. If ...
5
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. ...
Do you know how 2d matrix is stored in 1d memory? Try to map 2-dimensions into one. M[i][j]=M[n*i+j] , where n is the number of cols. This is the one way of converting 2-d indices into one 1-d index. Now, how will you convert 1-d index into 2-d indices? Try to use division and modulus to convert 1-d index into 2-d i...
Python solution for beginner|| easy & explained
reshape-the-matrix
0
1
# Complexity\n- Time complexity:\nO(r*c) \n\n- Dont use "[[0]* col] * row" for new matrix. This cannot be mutated for each cell since it only creates a single object for each row.\n- [i//c] gives the row number and [i%c] gives the coloum number \n# Code\n```\nclass Solution:\n def matrixReshape(self, mat: List[Lis...
3
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. ...
Do you know how 2d matrix is stored in 1d memory? Try to map 2-dimensions into one. M[i][j]=M[n*i+j] , where n is the number of cols. This is the one way of converting 2-d indices into one 1-d index. Now, how will you convert 1-d index into 2-d indices? Try to use division and modulus to convert 1-d index into 2-d...
Python solution for beginner|| easy & explained
reshape-the-matrix
0
1
# Complexity\n- Time complexity:\nO(r*c) \n\n- Dont use "[[0]* col] * row" for new matrix. This cannot be mutated for each cell since it only creates a single object for each row.\n- [i//c] gives the row number and [i%c] gives the coloum number \n# Code\n```\nclass Solution:\n def matrixReshape(self, mat: List[Lis...
3
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. ...
Do you know how 2d matrix is stored in 1d memory? Try to map 2-dimensions into one. M[i][j]=M[n*i+j] , where n is the number of cols. This is the one way of converting 2-d indices into one 1-d index. Now, how will you convert 1-d index into 2-d indices? Try to use division and modulus to convert 1-d index into 2-d i...
6 Lines of Code ----> python
reshape-the-matrix
0
1
\n# please upvote me it would encourage me alot\n\n```\nclass Solution:\n def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:\n list1,matrix=list(chain.from_iterable(mat)),[]\n if len(mat)*len(mat[0])!=r*c:\n return mat\n for i in range(0,len(list1),c):\...
10
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. ...
Do you know how 2d matrix is stored in 1d memory? Try to map 2-dimensions into one. M[i][j]=M[n*i+j] , where n is the number of cols. This is the one way of converting 2-d indices into one 1-d index. Now, how will you convert 1-d index into 2-d indices? Try to use division and modulus to convert 1-d index into 2-d...
6 Lines of Code ----> python
reshape-the-matrix
0
1
\n# please upvote me it would encourage me alot\n\n```\nclass Solution:\n def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:\n list1,matrix=list(chain.from_iterable(mat)),[]\n if len(mat)*len(mat[0])!=r*c:\n return mat\n for i in range(0,len(list1),c):\...
10
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. ...
Do you know how 2d matrix is stored in 1d memory? Try to map 2-dimensions into one. M[i][j]=M[n*i+j] , where n is the number of cols. This is the one way of converting 2-d indices into one 1-d index. Now, how will you convert 1-d index into 2-d indices? Try to use division and modulus to convert 1-d index into 2-d i...
Very Easy || 100% || Fully Explained || Java, C++, Python, JavaScript, Python3
reshape-the-matrix
1
1
# **Java Solution:**\n```\n// Runtime: 1 ms, faster than 92.33% of Java online submissions for Reshape the Matrix.\n// Time Complexity : O(r*c)\n// Space Complexity : O(r*c)\nclass Solution {\n public int[][] matrixReshape(int[][] mat, int r, int c) {\n // If transformation doesn\'t occur, return mat...\n ...
35
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. ...
Do you know how 2d matrix is stored in 1d memory? Try to map 2-dimensions into one. M[i][j]=M[n*i+j] , where n is the number of cols. This is the one way of converting 2-d indices into one 1-d index. Now, how will you convert 1-d index into 2-d indices? Try to use division and modulus to convert 1-d index into 2-d...
Very Easy || 100% || Fully Explained || Java, C++, Python, JavaScript, Python3
reshape-the-matrix
1
1
# **Java Solution:**\n```\n// Runtime: 1 ms, faster than 92.33% of Java online submissions for Reshape the Matrix.\n// Time Complexity : O(r*c)\n// Space Complexity : O(r*c)\nclass Solution {\n public int[][] matrixReshape(int[][] mat, int r, int c) {\n // If transformation doesn\'t occur, return mat...\n ...
35
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. ...
Do you know how 2d matrix is stored in 1d memory? Try to map 2-dimensions into one. M[i][j]=M[n*i+j] , where n is the number of cols. This is the one way of converting 2-d indices into one 1-d index. Now, how will you convert 1-d index into 2-d indices? Try to use division and modulus to convert 1-d index into 2-d i...
Best python solution easy to understand!!!
reshape-the-matrix
0
1
\n# Approach\n<!-- Describe your approach to solving the problem. --> First we should check if it is possible to reshape the given matrix to asked one. Then we make one dimensional array from given matrix (flat). After, we add the subarrays which are defined by dividing the flat array into c, r times .\n\n# Complexity\...
7
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. ...
Do you know how 2d matrix is stored in 1d memory? Try to map 2-dimensions into one. M[i][j]=M[n*i+j] , where n is the number of cols. This is the one way of converting 2-d indices into one 1-d index. Now, how will you convert 1-d index into 2-d indices? Try to use division and modulus to convert 1-d index into 2-d...
Best python solution easy to understand!!!
reshape-the-matrix
0
1
\n# Approach\n<!-- Describe your approach to solving the problem. --> First we should check if it is possible to reshape the given matrix to asked one. Then we make one dimensional array from given matrix (flat). After, we add the subarrays which are defined by dividing the flat array into c, r times .\n\n# Complexity\...
7
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. ...
Do you know how 2d matrix is stored in 1d memory? Try to map 2-dimensions into one. M[i][j]=M[n*i+j] , where n is the number of cols. This is the one way of converting 2-d indices into one 1-d index. Now, how will you convert 1-d index into 2-d indices? Try to use division and modulus to convert 1-d index into 2-d i...
✔️ [Python3] SLIDING WINDOW OPTIMIZED ( ❝̆ ·̫̮ ❝̆ )✧, Explained
permutation-in-string
0
1
**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**\n\nThe only thing we care about any particular substring in `s2` is having the same number of characters as in the `s1`. So we create a hashmap with the count of every character in the string `s1`. Then we slide a windo...
245
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:** **Input:** s1 = "ab ", s2 = "eidbaooo " **Output:** true **Explanation:** s2 contains one permuta...
Obviously, brute force will result in TLE. Think of something else. How will you check whether one string is a permutation of another string? One way is to sort the string and then compare. But, Is there a better way? If one string is a permutation of another string then they must one common metric. What is that? Both ...
Solution
permutation-in-string
1
1
```C++ []\nclass Solution {\npublic:\n bool checkInclusion(string s1, string s2) {\n vector<int>s1hash(26,0);\n vector<int>s2hash(26,0);\n if(s1.size()>s2.size())\n return 0;\n\n int left=0,right=0;\n while(right<s1.size())\n {\n s1hash[s1[right]-\'a\']...
1
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:** **Input:** s1 = "ab ", s2 = "eidbaooo " **Output:** true **Explanation:** s2 contains one permuta...
Obviously, brute force will result in TLE. Think of something else. How will you check whether one string is a permutation of another string? One way is to sort the string and then compare. But, Is there a better way? If one string is a permutation of another string then they must one common metric. What is that? Both ...
Best Explained Solution
permutation-in-string
1
1
\n```\nclass Solution {\n fun checkInclusion(s1: String, s2: String): Boolean {\n if (s1.length > s2.length) return false\n val s1map = IntArray(26)\n val s2map = IntArray(26)\n for (i in s1.indices) {\n s1map[s1[i] - \'a\']++\n s2map[s2[i] - \'a\']++\n }\n ...
1
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:** **Input:** s1 = "ab ", s2 = "eidbaooo " **Output:** true **Explanation:** s2 contains one permuta...
Obviously, brute force will result in TLE. Think of something else. How will you check whether one string is a permutation of another string? One way is to sort the string and then compare. But, Is there a better way? If one string is a permutation of another string then they must one common metric. What is that? Both ...
Best of C++, Java, Python
permutation-in-string
1
1
# Complexity\n- Time complexity: $$O(n + m)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$ \n`target` and `pending` are of fixed size regardless of input strings\' lengths.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```C++ []\nclass Solution {\npublic:\n...
1
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:** **Input:** s1 = "ab ", s2 = "eidbaooo " **Output:** true **Explanation:** s2 contains one permuta...
Obviously, brute force will result in TLE. Think of something else. How will you check whether one string is a permutation of another string? One way is to sort the string and then compare. But, Is there a better way? If one string is a permutation of another string then they must one common metric. What is that? Both ...
Python3 sort solution
permutation-in-string
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
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:** **Input:** s1 = "ab ", s2 = "eidbaooo " **Output:** true **Explanation:** s2 contains one permuta...
Obviously, brute force will result in TLE. Think of something else. How will you check whether one string is a permutation of another string? One way is to sort the string and then compare. But, Is there a better way? If one string is a permutation of another string then they must one common metric. What is that? Both ...
BFS✅| PYTHON ✅| O(N * M)| ✅
subtree-of-another-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSolving the problem requires you to iterate over the tree and check each node against the predetermined subRoot to see if the tree contains the subRoot. \n# Approach\n<!-- Describe your approach to solving the problem. -->\nTo solve this ...
1
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 als...
Which approach is better here- recursive or iterative? If recursive approach is better, can you write recursive function with its parameters? Two trees s and t are said to be identical if their root values are same and their left and right subtrees are identical. Can you write this in form of recursive formulae? Recurs...
BFS✅| PYTHON ✅| O(N * M)| ✅
subtree-of-another-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSolving the problem requires you to iterate over the tree and check each node against the predetermined subRoot to see if the tree contains the subRoot. \n# Approach\n<!-- Describe your approach to solving the problem. -->\nTo solve this ...
1
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 als...
Which approach is better here- recursive or iterative? If recursive approach is better, can you write recursive function with its parameters? Two trees s and t are said to be identical if their root values are same and their left and right subtrees are identical. Can you write this in form of recursive formulae? Recurs...