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 |
|---|---|---|---|---|---|---|---|
Python 3 || recursion, w/ explanation || T/M: 96% / 17% | minesweeper | 0 | 1 | ```\nclass Solution:\n def updateBoard(self, board, click):\n\n if board[click[0]][click[1]] == \'M\': # <-- handle case that\n board[click[0]][click[1]] = \'X\' ; return board # click is mined\n\n adjacent = lambda x,y : [(x+dx,y+dy) for dx in range(-1,2) for dy in range... | 5 | Let's play the minesweeper game ([Wikipedia](https://en.wikipedia.org/wiki/Minesweeper_(video_game)), [online game](http://minesweeperonline.com))!
You are given an `m x n` char matrix `board` representing the game board where:
* `'M'` represents an unrevealed mine,
* `'E'` represents an unrevealed empty square,
... | null |
Solution | minesweeper | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n vector<vector<char>> updateBoard(vector<vector<char>>& A, vector<int>& C) {\n int x=C[0],y=C[1];\n int n=A.size();\n int m=A[0].size();\n if(A[x][y]==\'M\'){\n A[x][y]=\'X\';\n return A;\n }\n vector<int> r={1,1,0,... | 3 | Let's play the minesweeper game ([Wikipedia](https://en.wikipedia.org/wiki/Minesweeper_(video_game)), [online game](http://minesweeperonline.com))!
You are given an `m x n` char matrix `board` representing the game board where:
* `'M'` represents an unrevealed mine,
* `'E'` represents an unrevealed empty square,
... | null |
Python3 recursive solution | minesweeper | 0 | 1 | ```\nclass Solution:\n def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:\n x,y = click[0],click[1]\n options = []\n if board[x][y] == "M":\n board[x][y] = "X"\n else:\n options = [(0,1),(0,-1),(1,0),(1,-1),(1,1),(-1,-1),(-1,0),(-1,1)... | 7 | Let's play the minesweeper game ([Wikipedia](https://en.wikipedia.org/wiki/Minesweeper_(video_game)), [online game](http://minesweeperonline.com))!
You are given an `m x n` char matrix `board` representing the game board where:
* `'M'` represents an unrevealed mine,
* `'E'` represents an unrevealed empty square,
... | null |
dfs solution | minesweeper | 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: O(mn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(mn)\n<!-- Add your space complexity here, e.g.... | 0 | Let's play the minesweeper game ([Wikipedia](https://en.wikipedia.org/wiki/Minesweeper_(video_game)), [online game](http://minesweeperonline.com))!
You are given an `m x n` char matrix `board` representing the game board where:
* `'M'` represents an unrevealed mine,
* `'E'` represents an unrevealed empty square,
... | null |
Python Simple | minesweeper | 0 | 1 | Using DFS to traverse the board.\n\n# Code\n```\nclass Solution:\n def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:\n def get_neighbors(node):\n neighbors = []\n row_delta = [-1, -1, 0, 1, 1, 1, 0, -1]\n col_delta = [0, 1, 1, 1, 0, -1, -1, -1... | 0 | Let's play the minesweeper game ([Wikipedia](https://en.wikipedia.org/wiki/Minesweeper_(video_game)), [online game](http://minesweeperonline.com))!
You are given an `m x n` char matrix `board` representing the game board where:
* `'M'` represents an unrevealed mine,
* `'E'` represents an unrevealed empty square,
... | null |
Python3 Solution | minimum-absolute-difference-in-bst | 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 getMinimumDifference(self, root: Optional[TreeNode]) -> int:\n def inorder(node):\n... | 1 | Given the `root` of a Binary Search Tree (BST), return _the minimum absolute difference between the values of any two different nodes in the tree_.
**Example 1:**
**Input:** root = \[4,2,6,1,3\]
**Output:** 1
**Example 2:**
**Input:** root = \[1,0,48,null,null,12,49\]
**Output:** 1
**Constraints:**
* The number... | null |
Python | Beats 98.9% using inorder traversal | minimum-absolute-difference-in-bst | 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 | Given the `root` of a Binary Search Tree (BST), return _the minimum absolute difference between the values of any two different nodes in the tree_.
**Example 1:**
**Input:** root = \[4,2,6,1,3\]
**Output:** 1
**Example 2:**
**Input:** root = \[1,0,48,null,null,12,49\]
**Output:** 1
**Constraints:**
* The number... | null |
Solution | k-diff-pairs-in-an-array | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int findPairs(vector<int>& nums, int k) {\n \n int ans=0;\n if(k==0){\n unordered_map<int,int> mp;\n for(auto i: nums) mp[i]++;\n for(auto i: mp) if(i.second>1) ans++;\n return ans;\n }\n sort(nums... | 1 | Given an array of integers `nums` and an integer `k`, return _the number of **unique** k-diff pairs in the array_.
A **k-diff** pair is an integer pair `(nums[i], nums[j])`, where the following are true:
* `0 <= i, j < nums.length`
* `i != j`
* `nums[i] - nums[j] == k`
**Notice** that `|val|` denotes the absol... | null |
✔️ Python O(n) Solution | 98% Faster | Easy Solution | K-diff Pairs in an Array | k-diff-pairs-in-an-array | 0 | 1 | **\uD83D\uDD3C IF YOU FIND THIS POST HELPFUL PLEASE UPVOTE \uD83D\uDC4D**\n\nVisit this blog to learn Python tips and techniques and to find a Leetcode solution with an explanation: https://www.python-techs.com/\n\n**Solution:**\n```\nclass Solution:\n def findPairs(self, nums: List[int], k: int) -> int:\n cn... | 36 | Given an array of integers `nums` and an integer `k`, return _the number of **unique** k-diff pairs in the array_.
A **k-diff** pair is an integer pair `(nums[i], nums[j])`, where the following are true:
* `0 <= i, j < nums.length`
* `i != j`
* `nums[i] - nums[j] == k`
**Notice** that `|val|` denotes the absol... | null |
Best soln beats 100% | encode-and-decode-tinyurl | 1 | 1 | # Best Beats 100%\n\n\n# Very Big difference b/w C and Python in C this code beats 100% but this not happen in Python\n\n# Code\n```\nchar* encode(char* longUrl) {\n return longUrl;\n}\nchar* decode(ch... | 1 | > Note: This is a companion problem to the [System Design](https://leetcode.com/discuss/interview-question/system-design/) problem: [Design TinyURL](https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyURL-)-System/).
TinyURL is a URL shortening service where you enter a URL such as `htt... | null |
Easy Python solution one liner for each func | encode-and-decode-tinyurl | 0 | 1 | # Easy python soln\n\n# Code\n```\nclass Codec:\n\n def encode(self, longUrl):\n return longUrl\n\n def decode(self, shortUrl):\n return shortUrl\n``` | 1 | > Note: This is a companion problem to the [System Design](https://leetcode.com/discuss/interview-question/system-design/) problem: [Design TinyURL](https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyURL-)-System/).
TinyURL is a URL shortening service where you enter a URL such as `htt... | null |
Solution | encode-and-decode-tinyurl | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n\n unordered_map<string, string> um;\n vector<int> digits;\n Solution(): digits(4) {}\n\n string hex = "0123456789abcdef";\n string encode(string longUrl) {\n string encoded;\n for(int d: digits)\n encoded += hex[d];\n int r = 1;\n ... | 2 | > Note: This is a companion problem to the [System Design](https://leetcode.com/discuss/interview-question/system-design/) problem: [Design TinyURL](https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyURL-)-System/).
TinyURL is a URL shortening service where you enter a URL such as `htt... | null |
39ms | Python solution | encode-and-decode-tinyurl | 0 | 1 | ```\nclass Codec:\n\n def __init__(self) -> None:\n self.hm: Dict[str, str] = dict()\n self.urlCounter: int = 0\n\n def encode(self, longUrl: str) -> str:\n """\n Encodes a URL to a shortened URL.\n """\n encoded = str(self.urlCounter)\n self.hm[encoded] = longUrl\... | 1 | > Note: This is a companion problem to the [System Design](https://leetcode.com/discuss/interview-question/system-design/) problem: [Design TinyURL](https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyURL-)-System/).
TinyURL is a URL shortening service where you enter a URL such as `htt... | null |
Explained (Random) Python3 easy understanding | encode-and-decode-tinyurl | 0 | 1 | Random string from string.ascii_lowercase + string.digits\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```\nclass Codec:\n def __init__(self):\n ... | 2 | > Note: This is a companion problem to the [System Design](https://leetcode.com/discuss/interview-question/system-design/) problem: [Design TinyURL](https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyURL-)-System/).
TinyURL is a URL shortening service where you enter a URL such as `htt... | null |
joke solution | encode-and-decode-tinyurl | 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 | > Note: This is a companion problem to the [System Design](https://leetcode.com/discuss/interview-question/system-design/) problem: [Design TinyURL](https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyURL-)-System/).
TinyURL is a URL shortening service where you enter a URL such as `htt... | null |
Python3 proper https:// tin.e/ URL | encode-and-decode-tinyurl | 0 | 1 | using the md5 hashing to provide a proper tiny(er)url.\n\nMost implementations being posted are not even valid URLs, like wtf?\n\nProperly is like 3 extra lines compared to the just return the given value. smh\n\n\n```\nimport hashlib\n\n\nclass Codec:\n def __init__(self):\n self.urls = {}\n\n def hash_to... | 15 | > Note: This is a companion problem to the [System Design](https://leetcode.com/discuss/interview-question/system-design/) problem: [Design TinyURL](https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyURL-)-System/).
TinyURL is a URL shortening service where you enter a URL such as `htt... | null |
535: Solution with step by step explanation | encode-and-decode-tinyurl | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nlong_to_short: a dictionary to store the mapping between long and short URLs.\nshort_to_long: a dictionary to store the mapping between short and long URLs.\nchar_set: a string of characters used to generate short codes.\nba... | 4 | > Note: This is a companion problem to the [System Design](https://leetcode.com/discuss/interview-question/system-design/) problem: [Design TinyURL](https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyURL-)-System/).
TinyURL is a URL shortening service where you enter a URL such as `htt... | null |
✅ Python Simple Solution using Fixed-length Key | encode-and-decode-tinyurl | 0 | 1 | The code creates a fixed-sized key of length 6. For this specific case, I am using the following char-set to generate each char of the key:\n`0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`\n\nThe length of char-set is **62**. With this char-set, we would be able to generate **62^6** combinations i. e... | 12 | > Note: This is a companion problem to the [System Design](https://leetcode.com/discuss/interview-question/system-design/) problem: [Design TinyURL](https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyURL-)-System/).
TinyURL is a URL shortening service where you enter a URL such as `htt... | null |
Solution | complex-number-multiplication | 1 | 1 | ```C++ []\nclass Solution {\n public:\n string complexNumberMultiply(string a, string b) {\n const auto& [A, B] = getRealAndImag(a);\n const auto& [C, D] = getRealAndImag(b);\n return to_string(A * C - B * D) + "+" + to_string(A * D + B * C) + "i";\n }\n private:\n pair<int, int> getRealAndImag(const string... | 1 | A [complex number](https://en.wikipedia.org/wiki/Complex_number) can be represented as a string on the form `"**real**+**imaginary**i "` where:
* `real` is the real part and is an integer in the range `[-100, 100]`.
* `imaginary` is the imaginary part and is an integer in the range `[-100, 100]`.
* `i2 == -1`.
... | null |
Python Splitting the Number | complex-number-multiplication | 0 | 1 | \n# Code\n```\nclass Solution:\n def complexNumberMultiply(self, num1: str, num2: str) -> str:\n x1,x2 = int(num1.split("+")[0]),int(num2.split("+")[0])\n y1,y2 = int(num1.split("+")[1][:-1]),int(num2.split("+")[1][:-1])\n \n sayi = (x1*x2) - (y1*y2)\n i = (x1*y2) + (x2*y1)\n \n... | 1 | A [complex number](https://en.wikipedia.org/wiki/Complex_number) can be represented as a string on the form `"**real**+**imaginary**i "` where:
* `real` is the real part and is an integer in the range `[-100, 100]`.
* `imaginary` is the imaginary part and is an integer in the range `[-100, 100]`.
* `i2 == -1`.
... | null |
537: Space 99.29%, Solution with step by step explanation | complex-number-multiplication | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Split num1 and num2 into their real and imaginary parts by finding the position of the + and i symbols in the strings using the index() method.\n\n2. Convert the real and imaginary parts of num1 and num2 from strings to i... | 3 | A [complex number](https://en.wikipedia.org/wiki/Complex_number) can be represented as a string on the form `"**real**+**imaginary**i "` where:
* `real` is the real part and is an integer in the range `[-100, 100]`.
* `imaginary` is the imaginary part and is an integer in the range `[-100, 100]`.
* `i2 == -1`.
... | null |
Python solution Easy and understandable | complex-number-multiplication | 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 | A [complex number](https://en.wikipedia.org/wiki/Complex_number) can be represented as a string on the form `"**real**+**imaginary**i "` where:
* `real` is the real part and is an integer in the range `[-100, 100]`.
* `imaginary` is the imaginary part and is an integer in the range `[-100, 100]`.
* `i2 == -1`.
... | null |
Python3 simple solution | complex-number-multiplication | 0 | 1 | ```\nclass Solution:\n def complexNumberMultiply(self, num1: str, num2: str) -> str:\n a1,b1 = num1.split(\'+\')\n a1 = int(a1)\n b1 = int(b1[:-1])\n a2,b2 = num2.split(\'+\')\n a2 = int(a2)\n b2 = int(b2[:-1])\n return str(a1*a2 + b1*b2*(-1)) + \'+\' + str(a1*b2 + a2... | 7 | A [complex number](https://en.wikipedia.org/wiki/Complex_number) can be represented as a string on the form `"**real**+**imaginary**i "` where:
* `real` is the real part and is an integer in the range `[-100, 100]`.
* `imaginary` is the imaginary part and is an integer in the range `[-100, 100]`.
* `i2 == -1`.
... | null |
Python clean solution using Object-Oriented Design | complex-number-multiplication | 0 | 1 | One liners are cute but it\'s much better to write understandable code\n\n```python\nclass ComplexNumber:\n def __init__(self, string):\n real, imaginary = string.split(\'+\')\n self.real = int(real)\n self.imaginary = int(imaginary[:-1])\n \n def __mul__(self, ... | 3 | A [complex number](https://en.wikipedia.org/wiki/Complex_number) can be represented as a string on the form `"**real**+**imaginary**i "` where:
* `real` is the real part and is an integer in the range `[-100, 100]`.
* `imaginary` is the imaginary part and is an integer in the range `[-100, 100]`.
* `i2 == -1`.
... | null |
Python3 DFS/ Recursive DFS | convert-bst-to-greater-tree | 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)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n - DFS - \n```\n# Definition for a binary tree node.\n# class TreeNode:\... | 1 | Given the `root` of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.
As a reminder, a _binary search tree_ is a tree that satisfies these constraints:
* The left subtree of a... | null |
Python3 easy solution || beats 99% || iterative approach | convert-bst-to-greater-tree | 0 | 1 | # Code\n```\nclass Solution:\n def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]: \n stack, summ, node = [], 0, root\n while stack or node:\n while node:\n stack.append(node)\n node = node.right\n node = stack.pop()\n ... | 1 | Given the `root` of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.
As a reminder, a _binary search tree_ is a tree that satisfies these constraints:
* The left subtree of a... | null |
✔️ [Python3] IN-ORDER DFS ( •́ .̫ •̀ ), Explained | convert-bst-to-greater-tree | 0 | 1 | **UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**\n\nThere are two important components here. First of all, for conversion, we need to know the sum of elements from the right subtree. And second, additional information about greater nodes from the parent node. So we cr... | 11 | Given the `root` of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.
As a reminder, a _binary search tree_ is a tree that satisfies these constraints:
* The left subtree of a... | null |
Solution | convert-bst-to-greater-tree | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n TreeNode* convertBST(TreeNode* root) {\n if(root == NULL) return NULL;\n int cs = 0;\n stack<TreeNode*> st;\n TreeNode* curr = root;\n while(curr != NULL or !st.empty())\n {\n while(curr != NULL)\n {\n ... | 2 | Given the `root` of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.
As a reminder, a _binary search tree_ is a tree that satisfies these constraints:
* The left subtree of a... | null |
Python 3 | DFS | Stack | 4 different solutions | convert-bst-to-greater-tree | 0 | 1 | \n# Code\n\n```python\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\n# DFS with global variable\nclass Solution:\n\n def __init__(self):\n self.greater = 0\n\... | 1 | Given the `root` of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.
As a reminder, a _binary search tree_ is a tree that satisfies these constraints:
* The left subtree of a... | null |
Python. faster than 100.00%. Explained, clear & Easy-understanding solution. O(n). Recursive | convert-bst-to-greater-tree | 0 | 1 | A tour of the tree, from right to left.\nAt each step add to the current node the value of the right tree, add to the amount we have accumulated so far the value of the current node, and add to each node in the left sub-tree the amount we have accumulated so far.\t\n\t\n\tclass Solution:\n\t\tdef convertBST(self, root:... | 13 | Given the `root` of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.
As a reminder, a _binary search tree_ is a tree that satisfies these constraints:
* The left subtree of a... | null |
python using datetime and timedelta || easy to understand | minimum-time-difference | 0 | 1 | ```\nfrom datetime import datetime\nclass Solution:\n def findMinDifference(self, t: List[str]) -> int:\n dates = []\n src = datetime.now()\n for time in t:\n h,m = map(int,time.split(\':\'))\n dates.append(datetime(src.year, src.month, src.day, h, m))\n dates.ap... | 1 | Given a list of 24-hour clock time points in **"HH:MM "** format, return _the minimum **minutes** difference between any two time-points in the list_.
**Example 1:**
**Input:** timePoints = \["23:59","00:00"\]
**Output:** 1
**Example 2:**
**Input:** timePoints = \["00:00","23:59","00:00"\]
**Output:** 0
**Constrai... | null |
Python3 clean solution using sorting | minimum-time-difference | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def findMinDifference(self, timePoints: List[str]) -> int:\n \n def convert(time):\n h=int(time[:2])\n m=int(time[3:])\n return h*60 + m\n \n \n l=[convert(t) for t in timePoints]\n l.sort()\n n=len(l... | 3 | Given a list of 24-hour clock time points in **"HH:MM "** format, return _the minimum **minutes** difference between any two time-points in the list_.
**Example 1:**
**Input:** timePoints = \["23:59","00:00"\]
**Output:** 1
**Example 2:**
**Input:** timePoints = \["00:00","23:59","00:00"\]
**Output:** 0
**Constrai... | null |
Python Beginner , very easy understanding | minimum-time-difference | 1 | 1 | ```\nclass Solution:\n def findMinDifference(self, time: List[str]) -> int:\n for i in range(len(time)):\n time[i]=time[i].split(\':\')\n time[i]=[int(time[i][0]),int(time[i][1])]\n\n mini=float(\'inf\')\n time.sort()\n for i in range(1,len(time)):\n mini=... | 1 | Given a list of 24-hour clock time points in **"HH:MM "** format, return _the minimum **minutes** difference between any two time-points in the list_.
**Example 1:**
**Input:** timePoints = \["23:59","00:00"\]
**Output:** 1
**Example 2:**
**Input:** timePoints = \["00:00","23:59","00:00"\]
**Output:** 0
**Constrai... | null |
Solution | minimum-time-difference | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int findMinDifference(vector<string>& timePoints) {\n vector<int> minutes;\n\n for(int i =0;i<timePoints.size();i++){\n string curr = timePoints[i];\n int hours = stoi (curr.substr(0,2));\n int min = stoi (curr.substr(3,2));\n ... | 1 | Given a list of 24-hour clock time points in **"HH:MM "** format, return _the minimum **minutes** difference between any two time-points in the list_.
**Example 1:**
**Input:** timePoints = \["23:59","00:00"\]
**Output:** 1
**Example 2:**
**Input:** timePoints = \["00:00","23:59","00:00"\]
**Output:** 0
**Constrai... | null |
[python 3] bucket sort, O(n) time, O(1) space | minimum-time-difference | 0 | 1 | ```\nclass Solution:\n def findMinDifference(self, timePoints: List[str]) -> int:\n M = 1440\n times = [False] * M\n for time in timePoints:\n minute = self.minute(time)\n if times[minute]:\n return 0\n times[minute] = True\n \n minut... | 11 | Given a list of 24-hour clock time points in **"HH:MM "** format, return _the minimum **minutes** difference between any two time-points in the list_.
**Example 1:**
**Input:** timePoints = \["23:59","00:00"\]
**Output:** 1
**Example 2:**
**Input:** timePoints = \["00:00","23:59","00:00"\]
**Output:** 0
**Constrai... | null |
Python Solution with Sorting and Two-pointers | minimum-time-difference | 0 | 1 | ```\nclass Solution:\n def findMinDifference(self, timePoints: List[str]) -> int:\n minutesConvert = []\n\t\t# convert time points to minutes expression\n for time in timePoints:\n t = time.split(":")\n minutes = int(t[0]) * 60 + int(t[1])\n minutesConvert.append(minute... | 1 | Given a list of 24-hour clock time points in **"HH:MM "** format, return _the minimum **minutes** difference between any two time-points in the list_.
**Example 1:**
**Input:** timePoints = \["23:59","00:00"\]
**Output:** 1
**Example 2:**
**Input:** timePoints = \["00:00","23:59","00:00"\]
**Output:** 0
**Constrai... | null |
Clean Python, O(n) vs O(n log n) Discussion, Shortcut for long inputs | minimum-time-difference | 0 | 1 | Why is complexity O(n) or O(n log n): This basically depends on whether you sort via counting sort. Counting sort could be considered an O(n) sorting algorithm for this problem, but it would have 60 x 24 = 1440 buckets. For reference: 530 x log(530) = 1443. Given that 2 <= timePoints.length <= 2 x 10^4, it could make s... | 10 | Given a list of 24-hour clock time points in **"HH:MM "** format, return _the minimum **minutes** difference between any two time-points in the list_.
**Example 1:**
**Input:** timePoints = \["23:59","00:00"\]
**Output:** 1
**Example 2:**
**Input:** timePoints = \["00:00","23:59","00:00"\]
**Output:** 0
**Constrai... | null |
539: Solution with step by step explanation | minimum-time-difference | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Convert the list of time points to a list of minutes since midnight by splitting the string into hours and minutes and converting them to integers. Store the result in a variable called minutes.\n2. Sort the list of minut... | 4 | Given a list of 24-hour clock time points in **"HH:MM "** format, return _the minimum **minutes** difference between any two time-points in the list_.
**Example 1:**
**Input:** timePoints = \["23:59","00:00"\]
**Output:** 1
**Example 2:**
**Input:** timePoints = \["00:00","23:59","00:00"\]
**Output:** 0
**Constrai... | null |
Easy & Clear Solution Python 3 | minimum-time-difference | 0 | 1 | ```\nclass Solution:\n def findMinDifference(self, t: List[str]) -> int:\n tab=[]\n for i in t:\n tab.append(int(i[0:2])*60+int(i[3:]))\n tab.sort()\n n=len(tab)\n res=1440+tab[0]-tab[n-1]\n for i in range(1,n):\n res=min(res,(tab[i]-tab[i-1]))\n ... | 16 | Given a list of 24-hour clock time points in **"HH:MM "** format, return _the minimum **minutes** difference between any two time-points in the list_.
**Example 1:**
**Input:** timePoints = \["23:59","00:00"\]
**Output:** 1
**Example 2:**
**Input:** timePoints = \["00:00","23:59","00:00"\]
**Output:** 0
**Constrai... | null |
Linear Search Approach | single-element-in-a-sorted-array | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAs the given array is sorted hence unique element will not match with its previous and next numbers(if exists).\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe search from element at index 1 upto index n-2 that ... | 2 | You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.
Return _the single element that appears only once_.
Your solution must run in `O(log n)` time and `O(1)` space.
**Example 1:**
**Input:** nums = \[1,1,2,3,3,4,4,8,8\... | null |
Day 52 || Binary Search || Easiest Beginner Friendly Sol | single-element-in-a-sorted-array | 1 | 1 | # Intuition of this Problem:\nSince every element in the sorted array appears exactly twice except for the single element, we know that if we take any element at an even index (0-indexed), the next element should be the same. Similarly, if we take any element at an odd index, the previous element should be the same. Th... | 456 | You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.
Return _the single element that appears only once_.
Your solution must run in `O(log n)` time and `O(1)` space.
**Example 1:**
**Input:** nums = \[1,1,2,3,3,4,4,8,8\... | null |
Most easy three lines solution | single-element-in-a-sorted-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)$$ --... | 1 | You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.
Return _the single element that appears only once_.
Your solution must run in `O(log n)` time and `O(1)` space.
**Example 1:**
**Input:** nums = \[1,1,2,3,3,4,4,8,8\... | null |
Binary Search || Python3 | single-element-in-a-sorted-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:O(logn)\n\n- Space complexity:O(1)\n\n# Code\n```\nclass Solution:\n def singleNonDuplicate(self, nums: List[int]) -> int:\n ... | 1 | You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.
Return _the single element that appears only once_.
Your solution must run in `O(log n)` time and `O(1)` space.
**Example 1:**
**Input:** nums = \[1,1,2,3,3,4,4,8,8\... | null |
Solution | single-element-in-a-sorted-array | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int singleNonDuplicate(vector<int>& nums) {\n ios_base::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL);\n\n int l=0,r=nums.size()-1,mid;\n while(l<r){\n mid=(l+r)/2;\n if(mid%2){\n if(nums[mid]!=nums[mid+1]) l... | 1 | You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.
Return _the single element that appears only once_.
Your solution must run in `O(log n)` time and `O(1)` space.
**Example 1:**
**Input:** nums = \[1,1,2,3,3,4,4,8,8\... | null |
Using Binary Search | single-element-in-a-sorted-array | 0 | 1 | # Intuition\nsince it sorted array, hence binary search is the first thing that comes to mind. \n\n# Approach\nInitialization is same as binary search. \n\nWhen you find the mid-index, we try to point the mid-index always to the second value of any number pair. which is done in the first **if** block inside the **while... | 1 | You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.
Return _the single element that appears only once_.
Your solution must run in `O(log n)` time and `O(1)` space.
**Example 1:**
**Input:** nums = \[1,1,2,3,3,4,4,8,8\... | null |
|| 🐍 Python3 Easiest ✔ Solution 🔥 || | single-element-in-a-sorted-array | 0 | 1 | # Approach\n1. Variable `n` is assigned the value of first number in list.\n2. A `for` loop is used to iterate through list from index 1 while we `XOR (^)` the numbers with `n`.\n - Since the numbers are in pair the `XOR` function will eliminate the pairs and only the unique element remains.\n\n# Complexity\n- Time ... | 1 | You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.
Return _the single element that appears only once_.
Your solution must run in `O(log n)` time and `O(1)` space.
**Example 1:**
**Input:** nums = \[1,1,2,3,3,4,4,8,8\... | null |
Simple to understanding python solution | single-element-in-a-sorted-array | 0 | 1 | ```python []\nclass Solution:\n def singleNonDuplicate(self, nums: List[int]) -> int:\n l, r = 0, len(nums) - 1\n\n while l <= r:\n m_l = m_r = m = (l + r) // 2\n if m > 0 and nums[m-1] == nums[m]:\n m_l = m - 1\n elif m + 1 < len(nums) and nums[m+1] == n... | 1 | You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.
Return _the single element that appears only once_.
Your solution must run in `O(log n)` time and `O(1)` space.
**Example 1:**
**Input:** nums = \[1,1,2,3,3,4,4,8,8\... | null |
Easiest python solution using binary search type logic | single-element-in-a-sorted-array | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach used in this algorithm is binary search. The key observation is that if an element is not the single non-duplicate, then it should be equal to its neighbor element, i.e., either the previous or the next element. Therefore, the elements wi... | 1 | You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.
Return _the single element that appears only once_.
Your solution must run in `O(log n)` time and `O(1)` space.
**Example 1:**
**Input:** nums = \[1,1,2,3,3,4,4,8,8\... | null |
75% faster O(n), 83% less mem. | single-element-in-a-sorted-array | 0 | 1 | # Intuition\nXOR\'em all\n\n# Approach\nI know, I know. I should implement bisect to get O(log n)...\nBut It would be a nice loffow up "what if input is not sorter", isn\'t it?\n\nIf you like it, please up-vote. Thank you!\n\n# Complexity\n- Time complexity: $$O(n)$$, yet 75% faster\n\n- Space complexity: $$O(1)$$, 82%... | 1 | You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.
Return _the single element that appears only once_.
Your solution must run in `O(log n)` time and `O(1)` space.
**Example 1:**
**Input:** nums = \[1,1,2,3,3,4,4,8,8\... | null |
python 2 pointer solution - easy for beginners | reverse-string-ii | 0 | 1 | # Code\n```\nclass Solution:\n def reverseStr(self, s: str, k: int) -> str:\n temp = []\n first = 0\n last = k-1 \n while (first <= len(s)-1): \n if last > len(s)-1:\n last = len(s) - 1\n while(last >= first): \n temp... | 1 | Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting from the start of the string.
If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than or equal to `k` characters, then reverse the first `k` characters and l... | null |
85% faster solution using Stack and Python | reverse-string-ii | 0 | 1 | # Intuition\n`2*k` is a strong clue for traversing through the string. This clue will help to divide the string into 2 stacks. Then the the job is to merge the two stacks. Before merging, reverse the subsring that matches the requirement of problem statement.\n\n# Approach\n- Divide the problem into 3 stacks. \n- one f... | 1 | Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting from the start of the string.
If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than or equal to `k` characters, then reverse the first `k` characters and l... | null |
✅Python3 33ms 🔥🔥 easiest solution | reverse-string-ii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWith help of blocks of string we can solve this.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- divide string in 2k blocks.\n- if length is less than k then reverse remainning and return.\n- now in 2k length blo... | 3 | Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting from the start of the string.
If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than or equal to `k` characters, then reverse the first `k` characters and l... | null |
✅ Easiest | | 6 lines Solution | | C++ | | Python ✅ | reverse-string-ii | 0 | 1 | # C++\n```\nclass Solution {\npublic:\n string reverseStr(string s, int k) {\n int l = 0,r = min(k,(int)s.length());\n\n while(l < s.length()){\n reverse(s.begin() + l,s.begin() + r);\n l += 2 * k;\n r = min(l + k,(int)s.length());\n }\n return s;\n }\n... | 3 | Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting from the start of the string.
If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than or equal to `k` characters, then reverse the first `k` characters and l... | null |
Python3 Simple Solution (6 lines) | reverse-string-ii | 0 | 1 | # Intuition\nThink of loop and iteration.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nIncremenet a variable by concatenating the substring of string.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity h... | 1 | Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting from the start of the string.
If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than or equal to `k` characters, then reverse the first `k` characters and l... | null |
Python3 Easy Solution With Comments | reverse-string-ii | 0 | 1 | \n# Approach\nThe reverseStr function takes two inputs, a string s and an integer k. It first converts the input string to a list of characters using the list() function. Then, it initializes a variable n to the length of the input string.\n\nThe function uses a while loop to iterate through the string with a step of 2... | 1 | Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting from the start of the string.
If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than or equal to `k` characters, then reverse the first `k` characters and l... | null |
easy to understand python solution | reverse-string-ii | 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 a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting from the start of the string.
If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than or equal to `k` characters, then reverse the first `k` characters and l... | null |
Simple and easy Python solution | reverse-string-ii | 0 | 1 | My concept is to for loop and split every 4 letter as a group,\neach group will reverse first 2 letter and add remaining letter.\neach loop Add word to the empty string call "sentence"\n```\nclass Solution:\n def reverseStr(self, s: str, k: int) -> str:\n sentence = ""\n for x in range(0, len(s), k+k):... | 6 | Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting from the start of the string.
If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than or equal to `k` characters, then reverse the first `k` characters and l... | null |
Python3, string ->List ->string | reverse-string-ii | 0 | 1 | ```\nclass Solution:\n def reverseStr(self, s: str, k: int) -> str:\n # Convert the input string into a list of characters\n mylist = list(s)\n \n # Iterate through the list with a step size of 2k\n for i in range(0, len(mylist), k + k):\n # Reverse the sublist of charac... | 4 | Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting from the start of the string.
If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than or equal to `k` characters, then reverse the first `k` characters and l... | null |
Python 97.68% beats 4line Code || Easy | reverse-string-ii | 0 | 1 | **If you got help from this,... Plz Upvote .. it encourage me**\n\n# Code\n```\nclass Solution:\n def reverseStr(self, s: str, k: int) -> str:\n s = list(s)\n for i in range(0,len(s),2*k):\n s[i:i+k] = reversed(s[i:i+k])\n return "".join(s)\n``` | 5 | Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting from the start of the string.
If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than or equal to `k` characters, then reverse the first `k` characters and l... | null |
Solution | reverse-string-ii | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n string reverseStr(string s, int k) {\n int len = s.size();\n\n int left = 0, right = 0;\n for(int i = 0; i < len; i += 2*k) {\n left = i;\n right = min(left + k - 1, len - 1);\n\n while(left <= right) {\n char... | 1 | Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting from the start of the string.
If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than or equal to `k` characters, then reverse the first `k` characters and l... | null |
✅ Explained - Simple and Clear Python3 Code✅ | reverse-string-ii | 0 | 1 | # Intuition\nThe problem requires us to reverse the first k characters for every 2k characters in a given string. To solve this, we can iterate over the string and use a list to store the reversed segments. By considering the pattern of reversing every 2k characters, we can determine the positions where the reversal ne... | 6 | Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting from the start of the string.
If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than or equal to `k` characters, then reverse the first `k` characters and l... | null |
Simple Python recursion solution (Beginner Friendly) | reverse-string-ii | 0 | 1 | ```\nclass Solution:\n def reverseStr(self, s: str, k: int) -> str:\n def reverse1(s, k):\n if len(s)<k:\n return s[::-1]\n if len(s)>=k and len(s)<=2*k:\n s1 = s[:k]; s2 = s[k:]\n s1 = list(s1)\n i = 0; j = len(s1)-1\n ... | 1 | Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting from the start of the string.
If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than or equal to `k` characters, then reverse the first `k` characters and l... | null |
Easy to understand Python solution to reverse string | reverse-string-ii | 0 | 1 | \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n# Code\n```\nclass Solution:\n def reverseStr(self, s: str, k: int) -> str:\n l = list(s)\n for i in range(0, len(l), 2 * k... | 2 | Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting from the start of the string.
If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than or equal to `k` characters, then reverse the first `k` characters and l... | null |
Python easy solution | reverse-string-ii | 0 | 1 | \n def reverseStr(self, s: str, k: int) -> str:\n s= list(s)\n for i in range(0,len(s),2*k):\n s[i:i+k] = s[i:i+k][::-1]\n return "".join(s) | 4 | Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting from the start of the string.
If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than or equal to `k` characters, then reverse the first `k` characters and l... | null |
Python short and clean. | 01-matrix | 0 | 1 | # Approach\nDo a two pass on the entire matrix, considering `left and top` while going `top-left to bottom-right`; `right and bottom` while going `bottom-right to top-left` corner.\n\n# Complexity\n- Time complexity: $$O(m \\cdot n)$$\n\n- Space complexity: $$O(m \\cdot n)$$\n\nwhere $$m \\times n$$ is the dimensions o... | 1 | Given an `m x n` binary matrix `mat`, return _the distance of the nearest_ `0` _for each cell_.
The distance between two adjacent cells is `1`.
**Example 1:**
**Input:** mat = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\]
**Output:** \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\]
**Example 2:**
**Input:** mat = \[\[0,0,0\],\[0,1,0\],\[1,1... | null |
Easiest Solution | 01-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 | Given an `m x n` binary matrix `mat`, return _the distance of the nearest_ `0` _for each cell_.
The distance between two adjacent cells is `1`.
**Example 1:**
**Input:** mat = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\]
**Output:** \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\]
**Example 2:**
**Input:** mat = \[\[0,0,0\],\[0,1,0\],\[1,1... | null |
Solution | 01-matrix | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {\n int n=mat.size();\n int m=mat[0].size();\n int t=m+n;\n int top,left;\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(!mat[i][j])continue;\n ... | 1 | Given an `m x n` binary matrix `mat`, return _the distance of the nearest_ `0` _for each cell_.
The distance between two adjacent cells is `1`.
**Example 1:**
**Input:** mat = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\]
**Output:** \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\]
**Example 2:**
**Input:** mat = \[\[0,0,0\],\[0,1,0\],\[1,1... | null |
✅ 94.87% Multi-source BFS + Queue | 01-matrix | 1 | 1 | # Problem Understanding\n\nIn the "01 Matrix Distance" problem, we are given a binary matrix, where each cell contains either a 0 or a 1. The task is to transform this matrix such that each cell contains the shortest distance to a cell with a 0.\n\nFor instance, given the matrix:\n\n$$\n\\text{mat} = \n\\begin{bmatrix}... | 91 | Given an `m x n` binary matrix `mat`, return _the distance of the nearest_ `0` _for each cell_.
The distance between two adjacent cells is `1`.
**Example 1:**
**Input:** mat = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\]
**Output:** \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\]
**Example 2:**
**Input:** mat = \[\[0,0,0\],\[0,1,0\],\[1,1... | null |
Python BFS Easy Solution with Explanation | 01-matrix | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n###### The goal is to get the nearest `0` for each `1`. So how can we get the nearest `0` for each `1`? Lets use `Multisource BFS` and `Dynamic Programming`.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n####... | 3 | Given an `m x n` binary matrix `mat`, return _the distance of the nearest_ `0` _for each cell_.
The distance between two adjacent cells is `1`.
**Example 1:**
**Input:** mat = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\]
**Output:** \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\]
**Example 2:**
**Input:** mat = \[\[0,0,0\],\[0,1,0\],\[1,1... | null |
C++/Python BFS w DP vs Forward & backward transversals | 01-matrix | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIt\'s a standard problem which can be solved by BFS.\n2nd approach is much easier which uses forward & backward transversals needs only O(1) SC.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. BFS uses a queue q. ... | 6 | Given an `m x n` binary matrix `mat`, return _the distance of the nearest_ `0` _for each cell_.
The distance between two adjacent cells is `1`.
**Example 1:**
**Input:** mat = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\]
**Output:** \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\]
**Example 2:**
**Input:** mat = \[\[0,0,0\],\[0,1,0\],\[1,1... | null |
Python Easy-to-understand solution w Explanation | diameter-of-binary-tree | 0 | 1 | ### Introduction\nConsider the first given example in the problem description:\n\n\n\nThe maximum depth of the left side of the tree is 2 (1 -> 2 -> 4/5), while the maximum depth of the right side of the tree i... | 204 | Given the `root` of a binary tree, return _the length of the **diameter** of the tree_.
The **diameter** of a binary tree is the **length** of the longest path between any two nodes in a tree. This path may or may not pass through the `root`.
The **length** of a path between two nodes is represented by the number of ... | null |
Depth-First Search✅ | O( n )✅ | (Step by step explanation)✅ | diameter-of-binary-tree | 0 | 1 | # Intuition\nThe problem is to find the diameter of a binary tree, which is the length of the longest path between any two nodes in a tree. The intuition is to perform a depth-first search (DFS) on the tree to calculate the height of the left and right subtrees for each node and maintain the maximum diameter found so f... | 6 | Given the `root` of a binary tree, return _the length of the **diameter** of the tree_.
The **diameter** of a binary tree is the **length** of the longest path between any two nodes in a tree. This path may or may not pass through the `root`.
The **length** of a path between two nodes is represented by the number of ... | null |
Most effective and simple recursive solution | diameter-of-binary-tree | 1 | 1 | \n\n# Approach\n- The height function calculates the height of a node in the binary tree.\n- For each node, it calculates the heights of its left and right subtrees (lh and rh).\n- Updates the diameter (ans) by comparing it with the sum of left and right subtree heights.\nuReturns the height of the current node (1 + ma... | 1 | Given the `root` of a binary tree, return _the length of the **diameter** of the tree_.
The **diameter** of a binary tree is the **length** of the longest path between any two nodes in a tree. This path may or may not pass through the `root`.
The **length** of a path between two nodes is represented by the number of ... | null |
Smart Approach | diameter-of-binary-tree | 0 | 1 | ```\nclass Solution:\n def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:\n ans=0\n def dia(root):\n nonlocal ans\n if not root:\n return 0\n left=dia(root.left)\n right=dia(root.right)\n ans=max(ans,left+right)\n ... | 4 | Given the `root` of a binary tree, return _the length of the **diameter** of the tree_.
The **diameter** of a binary tree is the **length** of the longest path between any two nodes in a tree. This path may or may not pass through the `root`.
The **length** of a path between two nodes is represented by the number of ... | null |
Solution | remove-boxes | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int dp[101][101][101];\n vector<vector<int>> group;\n\n int getDpVal(int l, int r, int k) {\n if(l > r) return 0;\n if(dp[l][r][k] != 0) return dp[l][r][k];\n int sz = group[l][1];\n int color = group[l][0];\n dp[l][r][k] = getDpVal(l + ... | 1 | You are given several `boxes` with different colors represented by different positive numbers.
You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of `k` boxes, `k >= 1`), remove them and get `k * k` points.
R... | null |
Python 3 || 11 lines, dp || T/M: 100% / 96% | remove-boxes | 0 | 1 | ```\nclass Solution:\n def removeBoxes(self, boxes: List[int]) -> int:\n\n boxes = tuple((k, len(list(g))) for k,g in groupby(boxes))\n\n @lru_cache(None)\n def dfs(grps: tuple) -> int:\n \n if not grps: return 0\n (colorL, lenL), grps = grps[0], grps[1:]\n\n ... | 4 | You are given several `boxes` with different colors represented by different positive numbers.
You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of `k` boxes, `k >= 1`), remove them and get `k * k` points.
R... | null |
546: Solution with step by step explanation | remove-boxes | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Define the removeBoxes function that takes in a list of boxes and returns an integer representing the maximum score that can be achieved by removing the boxes.\n\n2. Define the inner dp function that takes in the starting... | 3 | You are given several `boxes` with different colors represented by different positive numbers.
You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of `k` boxes, `k >= 1`), remove them and get `k * k` points.
R... | null |
546. Remove Boxes ( 100%°) | remove-boxes | 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 | You are given several `boxes` with different colors represented by different positive numbers.
You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of `k` boxes, `k >= 1`), remove them and get `k * k` points.
R... | null |
Simple Solution | remove-boxes | 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 sp... | 0 | You are given several `boxes` with different colors represented by different positive numbers.
You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of `k` boxes, `k >= 1`), remove them and get `k * k` points.
R... | null |
Solution | number-of-provinces | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int findCircleNum(vector<vector<int>>& isConnected) \n {\n int n = isConnected.size();\n std::vector<int> visited(n, 0);\n int groupCount = 0;\n for (int i = 0; i < n; ++i) \n {\n if (visited[i])\n continue;... | 2 | There are `n` cities. Some of them are connected, while some are not. If city `a` is connected directly with city `b`, and city `b` is connected directly with city `c`, then city `a` is connected indirectly with city `c`.
A **province** is a group of directly or indirectly connected cities and no other cities outside ... | null |
Union-Find with Path Compression, Python Solution beats 99% memory and 60% runtime | number-of-provinces | 0 | 1 | # Complexity\n- Time complexity: O(n ^ 2)\n\n- Space complexity: O(n ^ 2)\n# Code\n```\nclass UnionFind(object):\n\n def __init__(self, parents: list, rank: list):\n self.parents = parents\n self.rank = rank\n\n def find(self, node):\n\n parent = node \n while parent != self.parents[pa... | 2 | There are `n` cities. Some of them are connected, while some are not. If city `a` is connected directly with city `b`, and city `b` is connected directly with city `c`, then city `a` is connected indirectly with city `c`.
A **province** is a group of directly or indirectly connected cities and no other cities outside ... | null |
Solution | student-attendance-record-i | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n bool checkRecord(string s) {\n int absent=0,late=0;\n for(auto i:s){\n if(i==\'A\')\n absent++;\n }\n int cur=0;\n for(auto i:s)\n {\n if(i==\'L\')\n cur++;\n else{\n ... | 1 | You are given a string `s` representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:
* `'A'`: Absent.
* `'L'`: Late.
* `'P'`: Present.
The student is eligible for an attend... | null |
Easy to understand Python 1-liner O(n) | student-attendance-record-i | 0 | 1 | # Intuition\nFor string problems, see if you can solve them with built-in Python string methods. Often, it\'s much more Pythonic than iteration, even if iteration might have faster runtime. Also, note that we need only check if there is a run of 3 \'L\'s, as a run of more than 3 \'L\'s also contains a run of 3 L\'s.\n\... | 5 | You are given a string `s` representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:
* `'A'`: Absent.
* `'L'`: Late.
* `'P'`: Present.
The student is eligible for an attend... | null |
551: Space 92.86%, Solution with step by step explanation | student-attendance-record-i | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Initialize two variables, count_A and count_L, both to 0.\n2. Iterate through each character c in the input string s.\n3. If the character is \'A\', increment count_A and reset count_L to 0.\n4. If the character is \'L\',... | 5 | You are given a string `s` representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:
* `'A'`: Absent.
* `'L'`: Late.
* `'P'`: Present.
The student is eligible for an attend... | null |
Python one line simple solution | student-attendance-record-i | 0 | 1 | **Python :**\n\n```\ndef checkRecord(self, s: str) -> bool:\n\treturn False if "LLL" in s or s.count(\'A\') >= 2 else True\n```\n\n**Like it ? please upvote !** | 11 | You are given a string `s` representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:
* `'A'`: Absent.
* `'L'`: Late.
* `'P'`: Present.
The student is eligible for an attend... | null |
Solution | student-attendance-record-ii | 1 | 1 | ```C++ []\n#pragma clang attribute push (__attribute__((no_sanitize("address","undefined"))), apply_to=function)\n\nconst int mod = 1E9 + 7;\n\nint dp[2][3][4], ts;\narray<int, 2> t[1024];\n\nofstream out("user.out");\n\nint main() {\n ios::sync_with_stdio(0), cin.tie(0);\n for (int n; cin >> n; ts++) t[ts] = {n,... | 1 | An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:
* `'A'`: Absent.
* `'L'`: Late.
* `'P'`: Present.
Any student is eligible for an attendance awar... | null |
Python O(log n) using NumPy | student-attendance-record-ii | 0 | 1 | *This is an alternative writeup of [lixx2100\'s solution](https://leetcode.com/problems/student-attendance-record-ii/discuss/101633/Improving-the-runtime-from-O(n)-to-O(log-n)). Credit also to [StefanPochmann](https://leetcode.com/problems/student-attendance-record-ii/discuss/101633/Improving-the-runtime-from-O(n)-to-O... | 46 | An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:
* `'A'`: Absent.
* `'L'`: Late.
* `'P'`: Present.
Any student is eligible for an attendance awar... | null |
Easy to understand 7 line Python DP Solution | student-attendance-record-ii | 0 | 1 | # Intuition\nInitially, I thought that there might be a combinatorics based approach to this problem. However, the fact that there cannot be 3 L\'s in a row makes this hard. The next thing I thought of was DP, and indeed it works well here.\n\n# Approach\nLet $T(i, j, k)$ be the number of attendance records of length $... | 2 | An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:
* `'A'`: Absent.
* `'L'`: Late.
* `'P'`: Present.
Any student is eligible for an attendance awar... | null |
Top-Down DP - Python - Memoization - O(n) | student-attendance-record-ii | 0 | 1 | # Approach\nFirst solve the problem for only P and Ls.\nThis means, we have `n - 1` options for ending in Ps `(...LP, ...PP)`.\nThis also means, we have `n - 1` options for ending in Ls `(...LL, ...PL)`\n\nThis gives us for `n = 2 * helper(n - 1)`.\n\nBut we also have to incorporate constraints: No three `L` can follow... | 1 | An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:
* `'A'`: Absent.
* `'L'`: Late.
* `'P'`: Present.
Any student is eligible for an attendance awar... | null |
552: Solution with step by step explanation | student-attendance-record-ii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Initialize the modulo value kMod to 10**9 + 7.\n2. Create a 2D list dp of size 2 x 3 filled with zeros, where dp[i][j] represents the number of valid records with i A\'s and the latest j characters being L\'s.\n3. Set dp[... | 3 | An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:
* `'A'`: Absent.
* `'L'`: Late.
* `'P'`: Present.
Any student is eligible for an attendance awar... | null |
Python solution with explanation | student-attendance-record-ii | 0 | 1 | Here is a python solution with detailed expalanation:\n\n```\nclass Solution:\n def checkRecord(self, n: int) -> int:\n """\n Suppose dp[i] is the number of all the rewarded sequences without \'A\'\n having their length equals to i, then we have:\n 1. Number of sequence ends with \'P\... | 10 | An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:
* `'A'`: Absent.
* `'L'`: Late.
* `'P'`: Present.
Any student is eligible for an attendance awar... | null |
Solution in Python 3 (five lines) (with explanation) | student-attendance-record-ii | 0 | 1 | ```\nclass Solution:\n def checkRecord(self, n: int) -> int:\n \tC, m = [1,1,0,1,0,0], 10**9 + 7\n \tfor i in range(n-1):\n \t\ta, b = sum(C[:3]) % m, sum(C[3:]) % m\n \t\tC = [a, C[0], C[1], a + b, C[3], C[4]]\n \treturn (sum(C) % m)\n\t\t\n```\n_Explanation_\n\nThe list C is structured as follows:\n... | 16 | An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:
* `'A'`: Absent.
* `'L'`: Late.
* `'P'`: Present.
Any student is eligible for an attendance awar... | null |
Solution | optimal-division | 1 | 1 | ```C++ []\nclass Solution {\n public:\n string optimalDivision(vector<int>& nums) {\n string ans = to_string(nums[0]);\n\n if (nums.size() == 1)\n return ans;\n if (nums.size() == 2)\n return ans + "/" + to_string(nums[1]);\n\n ans += "/(" + to_string(nums[1]);\n for (int i = 2; i < nums.size(... | 2 | You are given an integer array `nums`. The adjacent integers in `nums` will perform the float division.
* For example, for `nums = [2,3,4]`, we will evaluate the expression `"2/3/4 "`.
However, you can add any number of parenthesis at any position to change the priority of operations. You want to add these parenthe... | null |
553: Solution with step by step explanation | optimal-division | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. If the length of the given array "nums" is 1, return the only number in the string format.\n2. If the length of the given array "nums" is 2, return the division of the first and second number in the string format.\n3. If ... | 2 | You are given an integer array `nums`. The adjacent integers in `nums` will perform the float division.
* For example, for `nums = [2,3,4]`, we will evaluate the expression `"2/3/4 "`.
However, you can add any number of parenthesis at any position to change the priority of operations. You want to add these parenthe... | null |
Python 3 Solution, Runtime beats 94% | optimal-division | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWhen len(nums)>=2, the first num in nums is dividend, and the rest of nums together form the divisor. In order to maximun the result, our strategy should be minimun the divisor.\n! That is a simple but not decent approach (from my perspec... | 0 | You are given an integer array `nums`. The adjacent integers in `nums` will perform the float division.
* For example, for `nums = [2,3,4]`, we will evaluate the expression `"2/3/4 "`.
However, you can add any number of parenthesis at any position to change the priority of operations. You want to add these parenthe... | null |
PYTHON EASY SOLUTION | Faster than 75% 📌🔥 | optimal-division | 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 | You are given an integer array `nums`. The adjacent integers in `nums` will perform the float division.
* For example, for `nums = [2,3,4]`, we will evaluate the expression `"2/3/4 "`.
However, you can add any number of parenthesis at any position to change the priority of operations. You want to add these parenthe... | null |
Easy string manipulation solution. | optimal-division | 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 | You are given an integer array `nums`. The adjacent integers in `nums` will perform the float division.
* For example, for `nums = [2,3,4]`, we will evaluate the expression `"2/3/4 "`.
However, you can add any number of parenthesis at any position to change the priority of operations. You want to add these parenthe... | null |
Python3 O(n) | optimal-division | 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 | You are given an integer array `nums`. The adjacent integers in `nums` will perform the float division.
* For example, for `nums = [2,3,4]`, we will evaluate the expression `"2/3/4 "`.
However, you can add any number of parenthesis at any position to change the priority of operations. You want to add these parenthe... | null |
Clear Python DP Solution with Faster than 50% | optimal-division | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSplit array to `Left` and `Right` parts, and then we can get max value of the whole array by `Left.max_val/Right.min_val` and the corresponding string by `"f{Left.max_str/Right.min_str}"`(There requires some ammendments on the min_str whi... | 0 | You are given an integer array `nums`. The adjacent integers in `nums` will perform the float division.
* For example, for `nums = [2,3,4]`, we will evaluate the expression `"2/3/4 "`.
However, you can add any number of parenthesis at any position to change the priority of operations. You want to add these parenthe... | null |
Python Dictionary With Explanation | brick-wall | 0 | 1 | # Intuition\nYou have to find the best coloumn basically through which we can draw a line so we cross the least number of walls.\nSo why not we store all the number of bricks which end at that particular coloumn.\n\n`Why? Because if we choose a coloumn where max brick ends then we have to cross the least number of bric... | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.