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
Simple simulation in Python3
robot-return-to-origin
0
1
# Intuition\nHere we have:\n- `moves` string and a robot\n- our goal is to move a robot from **origin**, which is `[0, 0]` by `moves` and check, if after all of the moves robot **returned** to a basic origin\n\nAn algorithm is quite simple: **simulate the process**, via mapping directions with integers (`U` and `L` as ...
1
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 `ith` move. Valid moves a...
null
Easy to understand Simple
robot-return-to-origin
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)$$ --...
2
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 `ith` move. Valid moves a...
null
Easy to understand Simple
robot-return-to-origin
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
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 `ith` move. Valid moves a...
null
Simplest Approach || Easily Understandable || Python and Java Solution
robot-return-to-origin
1
1
# Code\n```python []\nclass Solution:\n def judgeCircle(self, moves: str) -> bool:\n lr , ud = 0 , 0\n\n for move in moves:\n if move == \'U\':\n ud += 1\n elif move == \'D\':\n ud -= 1\n elif move == \'L\':\n lr += 1\n ...
8
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 `ith` move. Valid moves a...
null
Python 3, Very Easy
robot-return-to-origin
0
1
# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution:\n def judgeCircle(self, moves: str) -> bool:\n x: int = 0\n y: int = 0\n for move in moves:\n if move == \'U\':\n x += 1\n elif move == \'D\':\n x...
2
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 `ith` move. Valid moves a...
null
Python3 my first explained solution ✅✅✅ || Faster than 74.98% ⏩ || Memory beats 62.34(need help) 🧠
robot-return-to-origin
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI thought tracking the robot\'s coordinate would help me find it\'s current place, so I did track it\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can track every move the robot does. Since tuples are **immutabl...
2
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 `ith` move. Valid moves a...
null
(Java/Python3/JavaScript) three solutions
find-k-closest-elements
1
1
```\n# python3\nclass Solution:\n def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:\n\t\t# It\'s easy to write, but we need to sort it twice, so it\'s not the best way\n return sorted(sorted(arr, key = lambda v: abs(v-x))[:k])\n```\n```\n# python3\nclass Solution:\n def findCloses...
3
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: * `|a - x| < |b - x|`, or * `|a - x| == |b - x|` and `a < b` **Example 1:** **Input:...
null
Python || 2 Approaches || Min and Max Heap
find-k-closest-elements
0
1
```\n#Using Max Heap\nclass Solution:\n def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:\n pq=[]\n for i in range(len(arr)):\n d = -abs(x-arr[i]) \n if len(pq) < k: \n heapq.heappush(pq,(d,arr[i]))\n else:...
1
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: * `|a - x| < |b - x|`, or * `|a - x| == |b - x|` and `a < b` **Example 1:** **Input:...
null
Solution
split-array-into-consecutive-subsequences
1
1
```C++ []\nclass Solution {\n bool isSegmentPossible(vector<int>& nums, int startIdx, int endIdx)\n {\n vector<int> freq(nums[endIdx] - nums[startIdx] + 1);\n for (int i = startIdx; i <= endIdx; ++i)\n ++freq[nums[i]-nums[startIdx]];\n int lengthOneSubsequence = 0, lengthTwoSubsequ...
1
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: * Each subsequence is a **consecutive increasing sequence** (i.e. each integer is **exactly one** m...
null
Python 524ms 98.3% Faster Multiple solutions 94% memory efficient
split-array-into-consecutive-subsequences
0
1
# DON\'T FORGET TO UPVOTE!!!\n# 1. 98% faster 524 ms solution:\n\n\t\tclass Solution:\n\t\t\tdef isPossible(self, nums: List[int]) -> bool:\n\t\t\t\tlen1 = len2 = absorber = 0\n\t\t\t\tprev_num = nums[0] - 1\n\t\t\t\tfor streak_len, streak_num in Solution.get_streaks(nums):\n\t\t\t\t\tif streak_num == prev_num + 1:\n\t...
45
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: * Each subsequence is a **consecutive increasing sequence** (i.e. each integer is **exactly one** m...
null
Solution
image-smoother
1
1
```C++ []\nclass Solution {\npublic:\n\tvector<vector<int>> imageSmoother(vector<vector<int>>& img) {\n\t\tint m=img.size();\n\t\tint n=img[0].size();\n\t\tvector<vector<int>>mat=img;\n\t\tfor(int i=0;i<m;i++){\n\t\t\tfor(int j=0;j<n;j++){\n\t\t\t\tint sum=img[i][j];\n\t\t\t\tint count=1;\n\t\t\t\tif(i-1>=0){\n\t\t\t\t...
1
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 ...
null
661: Solution with step by step explanation
image-smoother
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Define a function called imageSmoother that takes in a 2D list of integers called img and returns a 2D list of integers.\n2. Get the dimensions of the original image by getting the length of img (number of rows) and the l...
5
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 ...
null
Python solution beats 90%
image-smoother
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe goal of this problem is to smooth an image by averaging the value of each pixel with its surrounding pixels. One way to achieve this is to iterate through each pixel in the image and average the values of the 8 neighboring pixels.\n# ...
3
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 ...
null
python 3 || clean and efficient solution
image-smoother
0
1
```\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 ...
9
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 ...
null
Python3 simple solution
image-smoother
0
1
```\nclass Solution:\n def imageSmoother(self, M: List[List[int]]) -> List[List[int]]:\n row, col = len(M), len(M[0])\n res = [[0]*col for i in range(row)]\n dirs = [[0,0],[0,1],[0,-1],[1,0],[-1,0],[1,1],[-1,-1],[-1,1],[1,-1]]\n for i in range(row):\n for j in range(col):\n ...
16
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 ...
null
Simple intuitive method
image-smoother
0
1
# Intuition\nRead the code.\nIf you cant understand it, get off of leetcode and go back to doing scratch; This is literally the most simple solution you will find.\n\n\n# Approach\nInitialise a zero matrix with the same dimensions as img, go through the matrix and take the average of all available surround points, set ...
0
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 ...
null
Intuitive approach - Python!
image-smoother
0
1
# Code\n```\nclass Solution:\n def imageSmoother(self, img: List[List[int]]) -> List[List[int]]:\n m, n, c = len(img), len(img[0]), 0\n ans = [[0 for _ in range(n)] for _ in range(m)]\n \n for i in range(m):\n rowStart, rowEnd = max(0, i - 1), min(m, i + 2)\n for j in range(n):\n ...
0
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 ...
null
Dead Easy Python Solution...!!!!!
image-smoother
0
1
# Dead Easy Python Solution\n\n# Code\n```\nclass Solution:\n def imageSmoother(self, img: List[List[int]]) -> List[List[int]]:\n n = len(img)\n m = len(img[0])\n ans = [[0]*m for i in range(n)]\n for row in range(n):\n for col in range(m):\n s = 0\n ...
0
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 ...
null
EASY PEASY PYTHON SOLUTION
image-smoother
0
1
# Code\n```\nclass Solution:\n def imageSmoother(self, img: List[List[int]]) -> List[List[int]]:\n m = len(img)\n n = len(img[0])\n def apply(img,start,end,m,n):\n i,j = start\n s,c = 0,0\n if i<0: i=0\n if i>m: i=m\n if j<0: j=0\n ...
0
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 ...
null
Simple solution with Python (BFS)
maximum-width-of-binary-tree
0
1
\n# Complexity\n- Time complexity: O(N+K) -> O(N), where N is count of root nodes and K is root depth\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(K) -> O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:...
1
Given the `root` of a binary tree, return _the **maximum width** of the given tree_. The **maximum width** of a tree is the maximum **width** among all levels. The **width** of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-no...
null
Python solution with node numbering
maximum-width-of-binary-tree
0
1
```\nJust number the nodes, like what we do to keep a tree in an array. \n\n root:x \nleft:2*x+1 right:2*x+2\n\nNow, this can get above the integer limit, but since our \nanswer is always withing the integer range, we can use mod \nhere. the difference of the rightmost and leftmost number is within in. \n\n*Als...
1
Given the `root` of a binary tree, return _the **maximum width** of the given tree_. The **maximum width** of a tree is the maximum **width** among all levels. The **width** of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-no...
null
Python3 👍||⚡89/95 faster beats 🔥|| clean solution || simple explain ||
maximum-width-of-binary-tree
0
1
![image.png](https://assets.leetcode.com/users/images/75d05e6c-7122-474e-8b87-834a0c72d588_1681976689.6991854.png)\n\n\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Sol...
1
Given the `root` of a binary tree, return _the **maximum width** of the given tree_. The **maximum width** of a tree is the maximum **width** among all levels. The **width** of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-no...
null
BFS || Binary Tree || Day 11 || PLEASE UPVOTE
maximum-width-of-binary-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 the `root` of a binary tree, return _the **maximum width** of the given tree_. The **maximum width** of a tree is the maximum **width** among all levels. The **width** of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-no...
null
✅✅Python🔥Java 🔥C++🔥Simple Solution🔥Easy to Understand🔥
maximum-width-of-binary-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. -->\nThe approach to solve this problem is to perform a level-order traversal of the binary tree using a queue. For each node, we calculate its corresponding index value ba...
1
Given the `root` of a binary tree, return _the **maximum width** of the given tree_. The **maximum width** of a tree is the maximum **width** among all levels. The **width** of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-no...
null
Python3 Solution
maximum-width-of-binary-tree
0
1
\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 widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:\n if root is None:\n ...
1
Given the `root` of a binary tree, return _the **maximum width** of the given tree_. The **maximum width** of a tree is the maximum **width** among all levels. The **width** of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-no...
null
Python BFS
maximum-width-of-binary-tree
0
1
# Approach\nBFS traversal while keeping track of each nodes index. The trick is that the index of the left child of a node x is 2 * index_of_x, and the index of the right child of a node x is (2 * index_of_x) + 1.\n\nThen, since we\'re doing BFS, we can just check the first (left) and last (right) node of each level. T...
1
Given the `root` of a binary tree, return _the **maximum width** of the given tree_. The **maximum width** of a tree is the maximum **width** among all levels. The **width** of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-no...
null
Solution
maximum-width-of-binary-tree
1
1
```C++ []\nclass Solution {\npublic:\n int widthOfBinaryTree(TreeNode* root) {\n long long int ans=0;\n if(root==NULL)return 0;\n \n queue<pair<TreeNode*,long long>> q;\n q.push({root,0});\n\n while(!q.empty()){\n int sz = q.size();\n long long int mini...
1
Given the `root` of a binary tree, return _the **maximum width** of the given tree_. The **maximum width** of a tree is the maximum **width** among all levels. The **width** of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-no...
null
Python Solution With Diagrams and Explanation
maximum-width-of-binary-tree
0
1
# Intuition\nInstead of keeping track of distance between each node.\nKeep track of "what could be the possible index"\n\nFor example \nIf we look at the example tree\n![image.png](https://assets.leetcode.com/users/images/dc27cc63-bffb-493e-93d6-2aeb2952f049_1681966705.9880064.png)\n\nWe could fill out our indexes as s...
8
Given the `root` of a binary tree, return _the **maximum width** of the given tree_. The **maximum width** of a tree is the maximum **width** among all levels. The **width** of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-no...
null
Python BFS
maximum-width-of-binary-tree
0
1
```\nclass Solution:\n def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:\n q, width = deque([(root, 0)]), 0\n while q:\n width = max(width, q[-1][1] - q[0][1])\n for _ in range(len(q)):\n node, k = q.popleft()\n if node.left:\n ...
12
Given the `root` of a binary tree, return _the **maximum width** of the given tree_. The **maximum width** of a tree is the maximum **width** among all levels. The **width** of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-no...
null
Image Explanation🏆- [Why long to int ??] - C++/Java/Python
maximum-width-of-binary-tree
1
1
# Video Solution (`Aryan Mittal`) - Link in LeetCode Profile\n`Maximum Width of Binary Tree` by `Aryan Mittal`\n![lc.png](https://assets.leetcode.com/users/images/94fedf53-397c-4d98-af10-2a3294d7aa3f_1681960611.903535.png)\n\n\n# Approach & Intution\n![image.png](https://assets.leetcode.com/users/images/da9eb2ad-cbc7-4...
139
Given the `root` of a binary tree, return _the **maximum width** of the given tree_. The **maximum width** of a tree is the maximum **width** among all levels. The **width** of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-no...
null
Python || Easy || BFS || O(n) Solution
maximum-width-of-binary-tree
0
1
```\nclass Solution:\n def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:\n if not root:\n return 0\n q=deque([[root,0]])\n ans=0\n while q:\n n=len(q)\n m=q[0][1]\n for i in range(n):\n node,index=q.popleft()\n ...
1
Given the `root` of a binary tree, return _the **maximum width** of the given tree_. The **maximum width** of a tree is the maximum **width** among all levels. The **width** of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-no...
null
Most efficient solution using bfs
maximum-width-of-binary-tree
1
1
\n\n# Approach\n- BFS Traversal with Position Tracking: Use BFS traversal to visit nodes in the binary tree. For each node, track its position in the current level. Nodes in the left subtree have positions 2 * curr - 1, and nodes in the right subtree have positions 2 * curr.\n\n- Position Calculation: When traversing t...
2
Given the `root` of a binary tree, return _the **maximum width** of the given tree_. The **maximum width** of a tree is the maximum **width** among all levels. The **width** of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-no...
null
Python3 Solution
strange-printer
0
1
\n```\nclass Solution:\n def strangePrinter(self, s: str) -> int:\n n=len(s)\n if not s:\n return 0\n\n dp=[[sys.maxsize]*n for _ in range(n)]\n\n for i in range(n):\n dp[i][i]=1\n\n for l in range(2,n+1):\n for i in range(n-l+1):\n j...
3
There is a strange printer with the following two special properties: * 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. Given a string `s`, return ...
null
[C++/Python/Rust] Divide and Conquer DP Solution
strange-printer
0
1
# Complexity\n- Time complexity: $$O(n ^ 3)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n ^ 2)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nconst int INF = 1e9;\n\nclass Solution {\npublic:\n int strangePrinter(string s) {\n int n = s....
1
There is a strange printer with the following two special properties: * 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. Given a string `s`, return ...
null
Python easy solutions || time & memory efficient
strange-printer
0
1
# Intuition\nThe problem seems to involve finding the minimum number of turns required to print a given string using a "strange printer." The printer can print a character on any substring of the given string and it can overlap with the existing characters. The objective is to minimize the number of turns to print the ...
1
There is a strange printer with the following two special properties: * 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. Given a string `s`, return ...
null
Solution
strange-printer
1
1
```C++ []\nclass Solution {\npublic:\n int dp[101][101];\n int helper(int l, int r, string &s){\n if(l>r) return 0;\n if(dp[l][r] != -1) return dp[l][r];\n int ans = INT_MAX;\n ans = min(ans, 1+helper(l+1, r, s));\n for(int i=l+1; i<=r; i++){\n if(s[i]==s[l]){\n ...
1
There is a strange printer with the following two special properties: * 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. Given a string `s`, return ...
null
🖨️ 100% Printer [VIDEO] 🔀 Peculiar : Minimizing Prints with Dynamic Programming 🔄📜
strange-printer
1
1
## Intuition\nWhen first encountering this problem, it seems to be a task of finding an optimal strategy for a sequence of actions. This is often a cue for a dynamic programming approach. In particular, the "strange" behavior of the printer (being able to print on top of existing characters and only printing the same c...
48
There is a strange printer with the following two special properties: * 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. Given a string `s`, return ...
null
Ex-Amazon explains a solution with a video, Python, JavaScript, Java and C++
strange-printer
1
1
# Intuition\nUsing dynamic programming to keep how many times the strange printer should print characters in current range between start and end.\n\n\n---\n\n\n# Solution Video\n## *** Please upvote for this article. *** \n\nhttps://youtu.be/bAS9rmAxBnI\n\n# Subscribe to my channel from here. I have 235 videos as of Ju...
16
There is a strange printer with the following two special properties: * 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. Given a string `s`, return ...
null
Python | Easy to Understand | Hard Problem | 664. Strange Printer
strange-printer
0
1
# Python | Easy to Understand | Hard Problem | 664. Strange Printer\n```\nclass Solution:\n def strangePrinter(self, s: str) -> int:\n N = len(s)\n @cache\n def calc(left, right): \n if left >= right: \n return 0\n best = calc(left + 1, right) + 1\n ...
24
There is a strange printer with the following two special properties: * 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. Given a string `s`, return ...
null
664: Space 93.43%, Solution with step by step explanation
strange-printer
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Get the length of the input string and store it in variable n.\n2. Create a n x n matrix called dp to store the minimum number of turns needed to print s[i:j+1].\n3. Loop backwards over the matrix to fill in the upper dia...
7
There is a strange printer with the following two special properties: * 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. Given a string `s`, return ...
null
Python Easy Greedy w/ explanation - O(1) space
non-decreasing-array
0
1
The approach that we will be taking is **greedy**. From the problem statement, it\'s clear that we have to count the number of violations i.e. **nums[i-1]>nums[i]**.\n\n> Input Array - **[1, 2, 4, 3]**\n> \nIn above case, we find one violation at index `3`. So this is a valid case, as we can make it non-decreasing by j...
64
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:** **Input:** nums = \[4,2,3\] **Output:...
null
Just Change the element
non-decreasing-array
0
1
```\nclass Solution:\n def checkPossibility(self, nums: List[int]) -> bool:\n count=0\n n=len(nums)\n for i in range(1,n):\n if nums[i]<nums[i-1]:\n count+=1\n if count>1:\n return False\n if i>=2 and nums[i-2]>nums[i]:\n...
3
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:** **Input:** nums = \[4,2,3\] **Output:...
null
THE BEST SOLUTION ON THE PLANET
non-decreasing-array
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
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:** **Input:** nums = \[4,2,3\] **Output:...
null
665: Time 96.74%, Solution with step by step explanation
non-decreasing-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. We start by initializing a count variable to keep track of the number of modifications we make.\n2. We then iterate through the array starting from the second element.\n3. For each element, we check if it is less than the...
3
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:** **Input:** nums = \[4,2,3\] **Output:...
null
Python3 | Explained | Easy to Understand | Non-decreasing Array
non-decreasing-array
0
1
```\nclass Solution:\n def checkPossibility(self, nums: List[int]) -> bool:\n is_modified = False # to check for multiple occurances of False condition(non increasing)\n index = -1 # to get the index of false condition\n n = len(nums)\n if n==1:return True\n ...
3
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:** **Input:** nums = \[4,2,3\] **Output:...
null
✔ Short & Easy Python3 Solution
non-decreasing-array
0
1
> Python3 Solution\n\n# Approach\n> Greedy\n\n\n# Code\n```\nclass Solution:\n def checkPossibility(self, nums: List[int]) -> bool:\n dummy=nums.copy()\n for i in range(1,len(nums)):\n if nums[i-1]>nums[i]:\n nums[i]=nums[i-1]\n dummy[i-1]=dummy[i]\n ...
1
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:** **Input:** nums = \[4,2,3\] **Output:...
null
Python 3, after 7 "Wrong Answer" attempts, explained with diagrams, O(n)
non-decreasing-array
0
1
After 7 failed attempts, here is the solution.\nBelow table shows a cople of simple examples with 1 and two elements in the array\n![image](https://assets.leetcode.com/users/images/f15665b6-d0c1-49f7-992b-9b0c7ad6448c_1607724642.1543553.png)\n\nBelow table shows a couple of examples with 3 elements.\n![image](https://a...
18
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:** **Input:** nums = \[4,2,3\] **Output:...
null
Solution
beautiful-arrangement-ii
1
1
```C++ []\nclass Solution {\npublic:\n vector<int> constructArray(int n, int k) {\n vector<int> ans;\n int i;\n for(i = 1; i <= n - k; i++)\n {\n ans.push_back(i);\n }\n int count = 0;\n for(int j = 0; j < k; j++)\n {\n if(j%2==0)\n ...
1
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: * Suppose this list is `answer = [a1, a2, a3, ... , an]`, then the list `[|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|]` has exactly `k` distinct ...
null
667: Solution with step by step explanation
beautiful-arrangement-ii
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Create an empty list called "ans".\n\n2. Add integers 1 through (n-k) to the "ans" list using the range() function.\n\n3. For each value of i in the range of 0 to k-1:\na. Calculate the difference between i and the neares...
2
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: * Suppose this list is `answer = [a1, a2, a3, ... , an]`, then the list `[|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|]` has exactly `k` distinct ...
null
Python solution
beautiful-arrangement-ii
0
1
\n# Code\n```\nclass Solution:\n def constructArray(self, n: int, k: int) -> List[int]:\n\n ans = list(range(1, n - k)) \n for i in range(k+1):\n if i % 2 == 0:\n ans.append(n-k + i//2)\n else:\n ans.append(n - i//2)\n\n return ans\n```
0
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: * Suppose this list is `answer = [a1, a2, a3, ... , an]`, then the list `[|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|]` has exactly `k` distinct ...
null
Not fast, but more explainable than original question! | Commented and Explained
beautiful-arrangement-ii
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nOur goal is to get all numbers in range 1 to n+1 \nWe need them in a \'beautiful\' order \nTo start, we know we can get the beginning of an answer by going from 1 to n-k values \nSo, we start our answer there \nThen, we know that we want ...
0
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: * Suppose this list is `answer = [a1, a2, a3, ... , an]`, then the list `[|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|]` has exactly `k` distinct ...
null
Solution
kth-smallest-number-in-multiplication-table
1
1
```C++ []\nclass Solution {\npublic:\n int findKthNumber(int m, int n, int k) {\n int l=1, L=m*n;\n while (L) {\n int d=L>>1;\n int x=l+d;\n int y=0;\n for (int a=n, b=0; a>0; --a) {\n while (b<=m and a*b<=x) ++b;\n y+=b-1;\n ...
1
Nearly everyone has used the [Multiplication Table](https://en.wikipedia.org/wiki/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_ `kth` _smallest element in the_ `m x n` _multipli...
null
668: Time 96.19%, Solution with step by step explanation
kth-smallest-number-in-multiplication-table
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Inside the binary_search function, use a while loop to iterate until left is no longer less than right.\n\n2. Calculate the middle index mid using the formula (left + right) // 2.\n\n3. Initialize a variable count to 0 an...
2
Nearly everyone has used the [Multiplication Table](https://en.wikipedia.org/wiki/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_ `kth` _smallest element in the_ `m x n` _multipli...
null
[ Python ] Clean & Most Efficient Binary Solution Beats 87.25% in runtime
kth-smallest-number-in-multiplication-table
0
1
\n# Code\n```\nclass Solution:\n def findKthNumber(self, m: int, n: int, k: int) -> int:\n def count(x):\n return sum(min(x//i, n) for i in range(1, m+1))\n\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 ...
2
Nearly everyone has used the [Multiplication Table](https://en.wikipedia.org/wiki/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_ `kth` _smallest element in the_ `m x n` _multipli...
null
[C++/Java/Python] Short Binary Search Solution with Explanation
kth-smallest-number-in-multiplication-table
1
1
### Introduction\n\nGiven a `m x n` multiplication table, we need to find the <code>k<sup>th</sup></code> smallest number in that table, where `1 <= k <= m*n`. But first, let\'s consider a different point-of-view: **if we are given a number `num` where `1 <= num <= m*n`, how do we find the number of numbers in the tabl...
110
Nearly everyone has used the [Multiplication Table](https://en.wikipedia.org/wiki/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_ `kth` _smallest element in the_ `m x n` _multipli...
null
python3 solution
kth-smallest-number-in-multiplication-table
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
Nearly everyone has used the [Multiplication Table](https://en.wikipedia.org/wiki/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_ `kth` _smallest element in the_ `m x n` _multipli...
null
Solution
trim-a-binary-search-tree
1
1
```C++ []\nclass Solution {\npublic:\n TreeNode* trimBST(TreeNode* root, int low, int high) {\n if(root==NULL) return NULL;\n if(root->val>=low&&root->val<=high){\n root->left=trimBST(root->left,low,high);\n root->right=trimBST(root->right,low,high);\n return root;\...
2
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 desce...
null
Recurssive solution using post order traversal
trim-a-binary-search-tree
0
1
# Approach\nKeep doing `post order traversal` and check for below conditions:\n`root.val < low`\nThis means current root and all the left node should be trimmed\n`root.val > high`\nThis means current root and all the right nodes should be trimmed\n`low <= root.val <= high`\nIn this case curretn root should be returned\...
1
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 desce...
null
Python. faster than 98.05%. recursive. 6 lines. DFS.
trim-a-binary-search-tree
0
1
\tclass Solution:\n\t\tdef trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode:\n\t\t\tif not root: return root\n\t\t\tif root.val < low: return self.trimBST(root.right, low, high)\n\t\t\tif root.val > high: return self.trimBST(root.left, low, high)\n\t\t\troot.left = self.trimBST(root.left, low, high)\n\t\t...
30
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 desce...
null
669: Solution with step by step explanation
trim-a-binary-search-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Initialize a while loop to find the new root of the trimmed tree. Iterate through the tree until we find a node that is within the boundaries of low and high.\n\n2. Check if the root is None. If it is, return None.\n\n3. ...
3
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 desce...
null
✅ Python || Easy Solution || 5 lines use recursive! || 100%
trim-a-binary-search-tree
0
1
* class Solution:\n\t\t\tdef trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]:\n\t\t\t\tif(root == None) : \n\t\t\t\t\treturn None; \n\t\t\t\troot.left = self.trimBST(root.left,low,high);\n\t\t\t\troot.right = self.trimBST(root.right,low,high); \n\t\t\t\tif( low <= root.va...
7
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 desce...
null
Easy to understand Python3 code with full explanation - O(n) time & O(n) space
maximum-swap
0
1
# Intuition\nBy eye-balling the question, we immediately have the intuition to swap the smallest left-most digit with the largest right-most digit in order to maximize the number . But how can we translate this into code?\n\nIf we iterate from left to right, we have to keep track of the left-most smallest digit and we ...
0
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:** **Input:** num = 2736 **Output:** 7236 **Explanation:** Swap the number 2 and the number 7. **Example 2:** **Input:** num = 9973 **Output:** 9973 **E...
null
String manipulation | Python3 | O(n)
maximum-swap
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nConvert the number to a string: The first step is to convert the given integer num into a string. This allows us to work with individual digits easily, making it convenient to iterate through the number digit by digit.\n\nFind the rightmo...
1
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:** **Input:** num = 2736 **Output:** 7236 **Explanation:** Swap the number 2 and the number 7. **Example 2:** **Input:** num = 9973 **Output:** 9973 **E...
null
Python 3 | Greedy, Math | Explanations
maximum-swap
0
1
### Explanation\n- Basic idea:\n\t- Find a index `i`, where there is a increasing order \n\t- On the right side of `i`, find the max value (`max_val`) and its index (`max_idx`)\n\t- On the left side of `i`, find the most left value and its index (`left_idx`), which is less than `max_val`\n\t- Swap above `left_idx` and ...
62
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:** **Input:** num = 2736 **Output:** 7236 **Explanation:** Swap the number 2 and the number 7. **Example 2:** **Input:** num = 9973 **Output:** 9973 **E...
null
670: Solution with step by step explanation
maximum-swap
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Convert the input integer num to a list of digits by using list(str(num)). This allows us to access each digit individually.\n\n2. Create a dictionary called last_seen that keeps track of the last index of each digit in t...
4
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:** **Input:** num = 2736 **Output:** 7236 **Explanation:** Swap the number 2 and the number 7. **Example 2:** **Input:** num = 9973 **Output:** 9973 **E...
null
Solution
maximum-swap
1
1
```C++ []\nclass Solution {\npublic:\n int maximumSwap(int num) {\n string digits = to_string(num);\n int left = 0, right = 0;\n int max_idx = digits.length() - 1;\n for (int i = digits.length() - 1; i >= 0; --i) {\n if (digits[i] > digits[max_idx]) {\n max_idx =...
4
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:** **Input:** num = 2736 **Output:** 7236 **Explanation:** Swap the number 2 and the number 7. **Example 2:** **Input:** num = 9973 **Output:** 9973 **E...
null
Intuitive | recursive | python 3
maximum-swap
0
1
Approach: \n1. Find the max of given array of digits.\n2. If max matches with the first digit (index 0) then there is no benefit of swapping, so recursively solve for remaining array i.e. index 1 onwards\n3. Else if - digit at index 0 is not equal to max of that array then swap it with the last occurance of max in t...
3
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:** **Input:** num = 2736 **Output:** 7236 **Explanation:** Swap the number 2 and the number 7. **Example 2:** **Input:** num = 9973 **Output:** 9973 **E...
null
Python 3 O(n) time, O(1) space, without using strings, with comments
maximum-swap
0
1
```\nclass Solution:\n def maximumSwap(self, num: int) -> int:\n # larger digit to swap, digit position of this digit\n high_digit = high_pos = 0\n \n # smaller digit to swap, digit position of this digit\n low_digit = low_pos = 0\n \n # greatest digit seen so far, di...
10
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:** **Input:** num = 2736 **Output:** 7236 **Explanation:** Swap the number 2 and the number 7. **Example 2:** **Input:** num = 9973 **Output:** 9973 **E...
null
Two Pointers || Explanation || Python
maximum-swap
0
1
# Intuition\nFirstly, I was thinking to appproach this problem as next greater but it will give wrong ans. Why? Suppose u found a bigger number later in string which can be interchanged with first one then that ans will give u correct ans.\neg => 782349\nnext greater swap will give == 872349\nans == 982347 \nhence u ha...
3
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:** **Input:** num = 2736 **Output:** 7236 **Explanation:** Swap the number 2 and the number 7. **Example 2:** **Input:** num = 9973 **Output:** 9973 **E...
null
python3 simple logic (with explanation)
maximum-swap
0
1
The greedy solution is to swap the leftmost digit with a larger digit to the right of it. For example, in 2237, 2 is swapped with 7, the largest digit to its right. \n\nHowever, what if there are multiple larger digits that are the same to the right? You should always swap with the rightmost one. For example, 89999 sho...
16
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:** **Input:** num = 2736 **Output:** 7236 **Explanation:** Swap the number 2 and the number 7. **Example 2:** **Input:** num = 9973 **Output:** 9973 **E...
null
671: Space 95.86%, Solution with step by step explanation
second-minimum-node-in-a-binary-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Initialize the minimum value and second minimum value to be the root value.\n\n2. Define a recursive helper function to explore the tree, taking a node as input.\n\n3. Within the helper function, use the nonlocal keyword ...
2
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.ri...
null
Simple Python Solution
second-minimum-node-in-a-binary-tree
0
1
# Code\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 findSecondMinimumValue(self, root: Optional[TreeNode]) -> int:\n def inorderT...
2
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.ri...
null
Python3 (DFS/DFS Recursive/ BFS)
second-minimum-node-in-a-binary-tree
0
1
\n\n# Complexity\n- Time complexity: O(1)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# ...
2
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.ri...
null
11 lines of code very easy approach
second-minimum-node-in-a-binary-tree
0
1
# Code\n```\nclass Solution:\n def findSecondMinimumValue(self, root: Optional[TreeNode]) -> int:\n if not root: return -1\n ar=set()\n def dfs(root):\n ar.add(root.val)\n if root.left: dfs(root.left)\n if root.right: dfs(root.right)\n dfs(root)\n a...
1
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.ri...
null
Simplest Python solution
second-minimum-node-in-a-binary-tree
0
1
\n\n# Code\n```\nclass Solution:\n def findSecondMinimumValue(self, root: Optional[TreeNode]) -> int:\n a = []\n\n def dfs(root):\n if not root:\n return\n dfs(root.left)\n a.append(root.val)\n dfs(root.right)\n\n dfs(root)\n\n re...
4
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.ri...
null
74% TC and 65% SC easy python solution
second-minimum-node-in-a-binary-tree
0
1
```\ndef findSecondMinimumValue(self, root: Optional[TreeNode]) -> int:\n\tleaf = set()\n\tdef dfs(node):\n\t\tif not(node.left):\n\t\t\tleaf.add(node.val)\n\t\t\treturn\n\t\tdfs(node.left)\n\t\tdfs(node.right)\n\tdfs(root)\n\treturn -1 if(len(leaf) < 2) else sorted(list(leaf))[1]\n```
2
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.ri...
null
SIMPLE PYTHON SOLUTION || UPTO 98 % FASTER
second-minimum-node-in-a-binary-tree
0
1
\n\n# Code\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 findSecondMinimumValue(self, root: Optional[TreeNode]) -> int:\n def trav...
1
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.ri...
null
672: Time 96.77%, Solution with step by step explanation
bulb-switcher-ii
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Reduce n to at most 3, since any action performed more than 3 times will result in a pattern that has already been counted.\n2. If m is 0, return 1 as there is only one possible outcome (all lights off).\n3. If m is 1, re...
3
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: * **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...
null
Python, BFS
bulb-switcher-ii
0
1
# Intuition\nWe need to traverse the states graph for exactly ``presses`` levels and get the total number of states discovered on the last level.\n\n# Approach\nWe can do either BFS or DFS. We also need an efficient way to represent a state and to calculate next states. \nWe can represent states as binary numbers where...
2
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: * **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...
null
O(1) with python. Pointless Question
bulb-switcher-ii
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMost stupid question I have ever done. First I thought it was recursion, then I thought it was a counting problem. Finally just found out it is just listing out all the cases. \n# Approach\n<!-- Describe your approach to solving the probl...
0
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: * **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...
null
Consider all cases, O(1)
bulb-switcher-ii
0
1
Straightforward to know that what matters is only n % 6.\nSuppose we have a,b,c,d operations of 1,2,3,4.\nBulb1 = (a+b+d) % 2\nBulb2 = (a+c) % 2\nBulb3 = (a+b) % 2\nand bulb 4 same as 1, 5 same as 3, 6 same as 2\n\nTherefore, what really matters is only the first three bulbs. \n\nIf we have only 1 bulb, in on step w...
0
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: * **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...
null
Easiest Solution
bulb-switcher-ii
1
1
\n\n# Code\n```java []\nclass Solution {\n\n public int flipLights(int n, int p) {\n n = Math.min(n, 4); \n p = Math.min(p, 4);\n int thre = (1<<n)-1;\n\n int[] flips = new int[] {\n Integer.parseInt("1111", 2)&thre,\n Integer.parseInt("0101", 2)&thre,\n I...
0
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: * **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...
null
Bit manipulation solution
bulb-switcher-ii
0
1
# Complexity\n- Time complexity:\n$$O(1)$$\n\n- Space complexity:\n$$O(m)$$. m is number of different states.\n\n# Code\n```\nclass Solution:\n def flipLights(self, n: int, presses: int) -> int:\n if presses == 0:\n return 1\n length = min(10, n)\n state = (1 << length) - 1\n b...
0
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: * **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...
null
Bit manipulation + BFS Rust and Python3 Solution
bulb-switcher-ii
0
1
### Rust Solution (passes)\n\n```\nuse std::collections::{HashSet, VecDeque};\n\nimpl Solution {\n fn flip_bit(number: i32, position: u32) -> i32 {\n let mask = 1 << position;\n let flipped_number = number ^ mask;\n flipped_number\n }\n \n fn y_function(x: i32) -> i32 {\n 3 * x ...
0
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: * **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...
null
Python3 Interview Feasible Solution
bulb-switcher-ii
0
1
## Inspired by [awice\'s post](https://leetcode.com/problems/bulb-switcher-ii/solutions/107267/Python-Straightforward-with-Explanation/)\n\n### 1. Observations:\n1. pressing a button twice -> nothing happen\n2. buttons order doesn\'t matter -> `Button1 + Button2` = `Button2 + Button1` \n\n### 2. Thought Processes:\nFo...
0
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: * **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...
null
Python | one-line O(1)
bulb-switcher-ii
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nJust try small cases and find a pattern. \n\n# Complexity\n- Time complexity: ```O(1)```\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: ```O(1)```\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n#...
0
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: * **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...
null
Identify the states of bulb for n=1,2,3 | O(1)
bulb-switcher-ii
0
1
```\nclass Solution:\n def flipLights(self, n: int, presses: int) -> int:\n """\n the trick to problem is that only 3 bulbs are indicative of all the n bulbs\n this is because, sequence repeats every 3 bulbs\n\n if n>3, then we can consider sequence of 3 bubls since that will reprsent the...
0
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: * **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...
null
Python3 Solution
number-of-longest-increasing-subsequence
0
1
\n```\nclass Solution:\n def findNumberOfLIS(self, nums: List[int]) -> int:\n n=len(nums)\n dp=[1]*n\n count=[1]*n\n for i in range(1,n):\n for j in range(i):\n if nums[i]>nums[j]:\n if 1+dp[j]>dp[i]:\n dp[i]=dp[j]+1\n\n ...
4
Given an integer array `nums`, return _the number of longest increasing subsequences._ **Notice** that the sequence has to be **strictly** increasing. **Example 1:** **Input:** nums = \[1,3,5,4,7\] **Output:** 2 **Explanation:** The two longest increasing subsequences are \[1, 3, 4, 7\] and \[1, 3, 5, 7\]. **Exampl...
null
BEST PYTHON SOLUTION FULL EXPLANATION 100%
number-of-longest-increasing-subsequence
0
1
# Intuition\n\nTo solve this problem, we can use dynamic programming to find the number of longest increasing subsequences (LIS) in the input list nums. We can maintain two arrays, dp1 and dp2, where dp1[i] represents the length of the LIS ending at index i, and dp2[i] represents the count of such LIS. We initialize bo...
2
Given an integer array `nums`, return _the number of longest increasing subsequences._ **Notice** that the sequence has to be **strictly** increasing. **Example 1:** **Input:** nums = \[1,3,5,4,7\] **Output:** 2 **Explanation:** The two longest increasing subsequences are \[1, 3, 4, 7\] and \[1, 3, 5, 7\]. **Exampl...
null
Python short and clean. 3 solutions. O(n . log(n)). Functional programming.
number-of-longest-increasing-subsequence
0
1
# Approach 1: Recursive DP\n\n# Complexity\n- Time complexity: $$O(n^2)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```python\nclass Solution:\n def findNumberOfLIS(self, nums: list[int]) -> int:\n n = len(nums)\n get = lambda xs, i: xs[i] if i < n else inf # To avoid using nums.append(inf)\n\n ...
1
Given an integer array `nums`, return _the number of longest increasing subsequences._ **Notice** that the sequence has to be **strictly** increasing. **Example 1:** **Input:** nums = \[1,3,5,4,7\] **Output:** 2 **Explanation:** The two longest increasing subsequences are \[1, 3, 4, 7\] and \[1, 3, 5, 7\]. **Exampl...
null
Python3 👍||⚡92% faster beats (984ms) 🔥|| different from other popular answers ||
number-of-longest-increasing-subsequence
0
1
![image.png](https://assets.leetcode.com/users/images/f9924688-f2d5-4df7-a5b6-45f4a5904fb2_1689959631.708924.png)\n\n\n\n# Complexity\n- Time complexity: O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclas...
1
Given an integer array `nums`, return _the number of longest increasing subsequences._ **Notice** that the sequence has to be **strictly** increasing. **Example 1:** **Input:** nums = \[1,3,5,4,7\] **Output:** 2 **Explanation:** The two longest increasing subsequences are \[1, 3, 4, 7\] and \[1, 3, 5, 7\]. **Exampl...
null
Python | Easy to Understand
number-of-longest-increasing-subsequence
0
1
# Intuition\nWe will use a dynamic programming approach to track the lengths and counts of increasing subsequences ending at each position in the array. The final answer will be the sum of the counts of subsequences with the maximum length.\n\n# Approach\n\n\n1. We initialize two lists `lengths` and `counts`, each with...
1
Given an integer array `nums`, return _the number of longest increasing subsequences._ **Notice** that the sequence has to be **strictly** increasing. **Example 1:** **Input:** nums = \[1,3,5,4,7\] **Output:** 2 **Explanation:** The two longest increasing subsequences are \[1, 3, 4, 7\] and \[1, 3, 5, 7\]. **Exampl...
null
Python | Easy to Understand | Medium Problem | 673. Number of Longest Increasing Subsequence
number-of-longest-increasing-subsequence
0
1
# Python | Easy to Understand | Medium Problem | 673. Number of Longest Increasing Subsequence\n```\nclass Solution:\n def findNumberOfLIS(self, nums: List[int]) -> int:\n if not nums: return 0\n n = len(nums)\n m, dp, cnt = 0, [1] * n, [1] * n\n for i in range(n):\n for j in r...
1
Given an integer array `nums`, return _the number of longest increasing subsequences._ **Notice** that the sequence has to be **strictly** increasing. **Example 1:** **Input:** nums = \[1,3,5,4,7\] **Output:** 2 **Explanation:** The two longest increasing subsequences are \[1, 3, 4, 7\] and \[1, 3, 5, 7\]. **Exampl...
null
🚀Beats 99.4% [VIDEO] | Cracking the Code DP - Longest Increasing Subsequences🔥
number-of-longest-increasing-subsequence
0
1
# Intuition\nUpon seeing this problem, I realized that it was a classic dynamic programming problem. It\'s about finding the number of longest strictly increasing subsequences in an array. A sequence is increasing if every number is larger than the one before. The intuition here was to keep track of two lists: one for ...
2
Given an integer array `nums`, return _the number of longest increasing subsequences._ **Notice** that the sequence has to be **strictly** increasing. **Example 1:** **Input:** nums = \[1,3,5,4,7\] **Output:** 2 **Explanation:** The two longest increasing subsequences are \[1, 3, 4, 7\] and \[1, 3, 5, 7\]. **Exampl...
null
🌿Efficient DP Solution | LIS | Beats 98.4%
number-of-longest-increasing-subsequence
1
1
# Intuition\nThe given problem can be efficiently solved using a dynamic programming approach. We maintain two arrays, dp and count, to keep track of the length of the longest increasing subsequence and the count of such subsequences, respectively. The idea is to iterate through the input array, updating these arrays a...
66
Given an integer array `nums`, return _the number of longest increasing subsequences._ **Notice** that the sequence has to be **strictly** increasing. **Example 1:** **Input:** nums = \[1,3,5,4,7\] **Output:** 2 **Explanation:** The two longest increasing subsequences are \[1, 3, 4, 7\] and \[1, 3, 5, 7\]. **Exampl...
null
Solution
number-of-longest-increasing-subsequence
1
1
```C++ []\nclass Solution {\npublic:\n int findNumberOfLIS(vector<int>& nums) {\n if (nums.empty()) {\n return 0;\n }\n vector<vector<pair<int, int>>> dyn(nums.size() + 1);\n int max_so_far = 0;\n for (int i = 0; i < nums.size(); ++i) {\n int l = 0, r = max_so...
2
Given an integer array `nums`, return _the number of longest increasing subsequences._ **Notice** that the sequence has to be **strictly** increasing. **Example 1:** **Input:** nums = \[1,3,5,4,7\] **Output:** 2 **Explanation:** The two longest increasing subsequences are \[1, 3, 4, 7\] and \[1, 3, 5, 7\]. **Exampl...
null
Python 3 | DP | Explanation
number-of-longest-increasing-subsequence
0
1
### Intuition\n- To find the frequency of the longest increasing sequence, we need \n\t- First, know how long is the longest increasing sequence\n\t- Second, count the frequency\n- Thus, we create 2 lists with length `n`\n\t- `dp[i]`: meaning length of longest increasing sequence\n\t- `cnt[i]`: meaning frequency of lon...
106
Given an integer array `nums`, return _the number of longest increasing subsequences._ **Notice** that the sequence has to be **strictly** increasing. **Example 1:** **Input:** nums = \[1,3,5,4,7\] **Output:** 2 **Explanation:** The two longest increasing subsequences are \[1, 3, 4, 7\] and \[1, 3, 5, 7\]. **Exampl...
null
Ex-Amazon explains a solution with a video, Python, JavaScript, Java and C++
number-of-longest-increasing-subsequence
1
1
# Intuition\nUsing Dynamic Programming to keep longest subsequences every iteration.\nThis solution beats 97%. \n\n![Screen Shot 2023-07-22 at 2.26.47.png](https://assets.leetcode.com/users/images/4be94a80-06ec-46af-980a-56e4df41c2f0_1689960430.558125.png)\n\n---\n\n# Solution Video\n*** Please upvote for this article....
7
Given an integer array `nums`, return _the number of longest increasing subsequences._ **Notice** that the sequence has to be **strictly** increasing. **Example 1:** **Input:** nums = \[1,3,5,4,7\] **Output:** 2 **Explanation:** The two longest increasing subsequences are \[1, 3, 4, 7\] and \[1, 3, 5, 7\]. **Exampl...
null
Python short 1-liner. Functional programming.
longest-continuous-increasing-subsequence
0
1
# Approach\n1. For each adjacent `pairwise` numbers in `nums` check if $$nums_i < nums_{i + 1}$$ to form a boolean array. (Useful to see bools as 1 and 0).\n`lt_bools = starmap(lt, pairwise(nums))`\n\n2. Calculate `running_sums` on the array of bools and reset every time a `0` is found.\n`run_sums = accumulate(lt_bools...
1
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], ..., num...
null
Beginners Python Code
longest-continuous-increasing-subsequence
0
1
# Code\n```\nclass Solution:\n def findLengthOfLCIS(self, nums: List[int]) -> int:\n n = len(nums)\n ans = 1\n curr_len = 1\n for i in range(1,n):\n if nums[i] > nums[i-1]:\n curr_len = curr_len + 1\n ans = max(ans,curr_len)\n else:\n ...
2
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], ..., num...
null