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
1-Line Python Solution || 96% Faster (68ms) || Memory less than 90%
range-addition-ii
0
1
```\nclass Solution:\n def maxCount(self, m: int, n: int, ops: List[List[int]]) -> int:\n return min([x for x,y in ops])*min([y for x,y in ops]) if ops else m*n\n```\n-------------------\n***----- Taha Choura -----***\n*taha.choura@outlook.com*
4
You are given an `m x n` matrix `M` initialized with all `0`'s and an array of operations `ops`, where `ops[i] = [ai, bi]` means `M[x][y]` should be incremented by one for all `0 <= x < ai` and `0 <= y < bi`. Count and return _the number of maximum integers in the matrix after performing all the operations_. **Exampl...
null
Python Brute Force Solution
minimum-index-sum-of-two-lists
0
1
# Intuition\nbeats 99.9%\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nBrute force\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(log n)\n\n- Space complexity:\n<!-- Add yo...
1
Given two arrays of strings `list1` and `list2`, find the **common strings with the least index sum**. A **common string** is a string that appeared in both `list1` and `list2`. A **common string with the least index sum** is a common string such that if it appeared at `list1[i]` and `list2[j]` then `i + j` should be...
null
Easily Understandable Python Code || Brute Force Approach
minimum-index-sum-of-two-lists
0
1
\n\n# Code\n```\nclass Solution:\n def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:\n m = len(list1) + len(list2)\n list3 = []\n \n for i in range(len(list1)):\n for j in range(len(list2)):\n if list1[i] == list2[j]:\n ...
2
Given two arrays of strings `list1` and `list2`, find the **common strings with the least index sum**. A **common string** is a string that appeared in both `list1` and `list2`. A **common string with the least index sum** is a common string such that if it appeared at `list1[i]` and `list2[j]` then `i + j` should be...
null
Solution
minimum-index-sum-of-two-lists
1
1
```C++ []\nclass Solution {\npublic:\n vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {\n unordered_map<string,int> mp,m;\n vector<string> v;\n int mini =INT_MAX;\n int mi;\n int sum;\n for(int i=0;i<list1.size();i++)\n m[list1[i]] = i...
2
Given two arrays of strings `list1` and `list2`, find the **common strings with the least index sum**. A **common string** is a string that appeared in both `list1` and `list2`. A **common string with the least index sum** is a common string such that if it appeared at `list1[i]` and `list2[j]` then `i + j` should be...
null
Python3 easy-peasy solution
minimum-index-sum-of-two-lists
0
1
# Intuition\nThe time complexity of both solutions is O(m * n), where m and n are the lengths of the two input lists. In the worst case, we have to compare every element of list1 to every element of list2 to find the common strings, which requires m * n comparisons. However, both solutions use a dictionary to keep trac...
1
Given two arrays of strings `list1` and `list2`, find the **common strings with the least index sum**. A **common string** is a string that appeared in both `list1` and `list2`. A **common string with the least index sum** is a common string such that if it appeared at `list1[i]` and `list2[j]` then `i + j` should be...
null
Python3|| Beats 99.13% || Using Dictionary(simple solution).
minimum-index-sum-of-two-lists
0
1
# Please do upvote if you find the solution helpful.\n![image.png](https://assets.leetcode.com/users/images/07c5515b-82e4-4a49-9f04-628782ab3768_1678213943.2728896.png)\n\n\n# Code\n```\nclass Solution:\n def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:\n d={}\n for i in range...
4
Given two arrays of strings `list1` and `list2`, find the **common strings with the least index sum**. A **common string** is a string that appeared in both `list1` and `list2`. A **common string with the least index sum** is a common string such that if it appeared at `list1[i]` and `list2[j]` then `i + j` should be...
null
599: Solution with step by step explanation
minimum-index-sum-of-two-lists
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nFind the common elements between both lists using the set intersection operator & and store the result in a variable called common.\n\nInitialize a dictionary called index_sum to store the index sum of common elements in lis...
8
Given two arrays of strings `list1` and `list2`, find the **common strings with the least index sum**. A **common string** is a string that appeared in both `list1` and `list2`. A **common string with the least index sum** is a common string such that if it appeared at `list1[i]` and `list2[j]` then `i + j` should be...
null
easy solution
minimum-index-sum-of-two-lists
1
1
\n\n# Code\n```java []\nclass Solution {\n public String[] findRestaurant(String[] list1, String[] list2) {\n Map<String,Integer> map=new HashMap<>();\n List<String> list=new ArrayList<>();\n int sum=Integer.MAX_VALUE;\n for(int i=0;i<list1.length;i++) map.put(list1[i],i);\n for(in...
2
Given two arrays of strings `list1` and `list2`, find the **common strings with the least index sum**. A **common string** is a string that appeared in both `list1` and `list2`. A **common string with the least index sum** is a common string such that if it appeared at `list1[i]` and `list2[j]` then `i + j` should be...
null
Python3 || Dictionary || single loop || Easy solution
minimum-index-sum-of-two-lists
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n\nUse dict .\n\n1.In for loop iterarte either list1 or list2 by using enumerate().\n\n2.Ckeck if word exists in second list, if so assign word as dict`s key and sum of word`s index and index given by index() as dict`s value....
1
Given two arrays of strings `list1` and `list2`, find the **common strings with the least index sum**. A **common string** is a string that appeared in both `list1` and `list2`. A **common string with the least index sum** is a common string such that if it appeared at `list1[i]` and `list2[j]` then `i + j` should be...
null
Python easy solution for beginners using lists only
minimum-index-sum-of-two-lists
0
1
```\nclass Solution:\n def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:\n res = []\n min_ind_sum = -1\n if len(list1) < len(list2):\n for i in range(len(list1)):\n if list1[i] in list2:\n ind_sum = i + list2.index(list1[i])\n...
1
Given two arrays of strings `list1` and `list2`, find the **common strings with the least index sum**. A **common string** is a string that appeared in both `list1` and `list2`. A **common string with the least index sum** is a common string such that if it appeared at `list1[i]` and `list2[j]` then `i + j` should be...
null
600: Solution with step by step explanation
non-negative-integers-without-consecutive-ones
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nInitialize a list f to store the fibonacci numbers 1 and 2.\n\nUse a loop to append the next 29 fibonacci numbers to f.\n\nInitialize two variables ans and last_seen to 0.\n\nUse a loop to iterate through all 31 bits of n, s...
2
Given a positive integer `n`, return the number of the integers in the range `[0, n]` whose binary representations **do not** contain consecutive ones. **Example 1:** **Input:** n = 5 **Output:** 5 **Explanation:** Here are the non-negative integers <= 5 with their corresponding binary representations: 0 : 0 1 : 1 2 ...
null
Solution
non-negative-integers-without-consecutive-ones
1
1
```C++ []\nclass Solution {\npublic:\n int findIntegers(int n) {\n int fib[31];\n fib[0] = 1;\n fib[1] = 2;\n\n for(int i=2; i<30; i++){\n fib[i] = fib[i-1]+fib[i-2];\n }\n int count = 30, ans = 0, prevOne = 0;\n while(count >= 0){\n if(n&(1<<cou...
1
Given a positive integer `n`, return the number of the integers in the range `[0, n]` whose binary representations **do not** contain consecutive ones. **Example 1:** **Input:** n = 5 **Output:** 5 **Explanation:** Here are the non-negative integers <= 5 with their corresponding binary representations: 0 : 0 1 : 1 2 ...
null
python clean & simple solution ✅ | | fibonacci approach 39ms 🔥🔥🔥
non-negative-integers-without-consecutive-ones
0
1
\n\n# Code\n```\nclass Solution:\n def findIntegers(self, n: int) -> int:\n f = [1,2]\n for i in range(2,30):\n f.append(f[-1] + f[-2])\n \n ans = last_seen = 0\n\n for i in range(29,-1,-1):\n if (1 << i) & n:\n ans += f[i]\n if l...
3
Given a positive integer `n`, return the number of the integers in the range `[0, n]` whose binary representations **do not** contain consecutive ones. **Example 1:** **Input:** n = 5 **Output:** 5 **Explanation:** Here are the non-negative integers <= 5 with their corresponding binary representations: 0 : 0 1 : 1 2 ...
null
[Python3] Official Solution Explained Simply with Diagrams
non-negative-integers-without-consecutive-ones
0
1
## 0. Introduction\nThe problem is hard, but looks deceptively easy. The solution is easy, but hard to understand. I\'ll attempt to explain the [official solution](https://leetcode.com/problems/non-negative-integers-without-consecutive-ones/solution/) with diagrams.\n\n## 1. The World of Bits\nThe single constraint giv...
109
Given a positive integer `n`, return the number of the integers in the range `[0, n]` whose binary representations **do not** contain consecutive ones. **Example 1:** **Input:** n = 5 **Output:** 5 **Explanation:** Here are the non-negative integers <= 5 with their corresponding binary representations: 0 : 0 1 : 1 2 ...
null
Solution to 600. Non-negative Integers without Consecutive Ones
non-negative-integers-without-consecutive-ones
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires finding the count of non-negative integers in the range [0, n] whose binary representations do not contain consecutive ones. To achieve this, we need a strategy to count the valid binary representations efficiently.\n...
0
Given a positive integer `n`, return the number of the integers in the range `[0, n]` whose binary representations **do not** contain consecutive ones. **Example 1:** **Input:** n = 5 **Output:** 5 **Explanation:** Here are the non-negative integers <= 5 with their corresponding binary representations: 0 : 0 1 : 1 2 ...
null
Time and space complexity very cool
can-place-flowers
0
1
if you want to help, you can subscribe to my twitch: www.twitch.tv/edexade\n\n# Code\n```\nclass Solution:\n def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:\n if n == 0:\n return True\n flowerbed.append(0)\n k = 0\n i = 0\n while i < len(flowerbed)-1:\n ...
1
You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in **adjacent** plots. Given an integer array `flowerbed` containing `0`'s and `1`'s, where `0` means empty and `1` means not empty, and an integer `n`, return `true` _if_ `n` _new flowers can be plan...
null
Simple Python3 Solution || Brute Force || O(n) || Upto 50% Faster
can-place-flowers
0
1
# Intuition\nOne possible solution to the problem is to iterate over the elements of the flowerbed array and check if the current plot and its adjacent plots are empty. If they are, plant a flower and increase the value of valid_slots. \nAt the end, return True if n is less than or equal to valid_slots, otherwise retur...
1
You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in **adjacent** plots. Given an integer array `flowerbed` containing `0`'s and `1`'s, where `0` means empty and `1` means not empty, and an integer `n`, return `true` _if_ `n` _new flowers can be plan...
null
✅✅Python Simple Solution 🔥🔥 Easy to Understand🔥🔥
can-place-flowers
0
1
# Please UPVOTE \uD83D\uDC4D\n\n**!! BIG ANNOUNCEMENT !!**\nI am Giving away my premium content videos related to computer science and data science and also will be sharing well-structured assignments and study materials to clear interviews at top companies to my first 1000 Subscribers. So, **DON\'T FORGET** to Subscri...
256
You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in **adjacent** plots. Given an integer array `flowerbed` containing `0`'s and `1`'s, where `0` means empty and `1` means not empty, and an integer `n`, return `true` _if_ `n` _new flowers can be plan...
null
Not a optimized solution
can-place-flowers
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 have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in **adjacent** plots. Given an integer array `flowerbed` containing `0`'s and `1`'s, where `0` means empty and `1` means not empty, and an integer `n`, return `true` _if_ `n` _new flowers can be plan...
null
🔥More Than One Method🔥| Java | C++ | Python | JavaScript |
construct-string-from-binary-tree
1
1
# 1st Method :- DFS\uD83D\uDD25\n\n## \u2712\uFE0FCode\n``` Java []\nclass Solution {\n public String tree2str(TreeNode root) {\n if (root == null) {\n return "";\n }\n \n // Step 1: Start with an empty result string\n StringBuilder result = new StringBuilder();\n ...
39
Given the `root` of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it. Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the original binary tree. **Example 1:** *...
null
✅☑[C++/Java/Python/JavaScript] || Easy Approach || EXPLAINED🔥
construct-string-from-binary-tree
1
1
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n\n\n1. **Preorder Traversal (pre Function):**\n\n - The `pre` function performs a preorder traversal of the binary tree.\n - At each node, it appends the node\'s value to the `ans` string.\n - If the node has either a le...
11
Given the `root` of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it. Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the original binary tree. **Example 1:** *...
null
😎 𝖇𝖊𝖆𝖙𝖘 100% | 𝕾𝖎𝖒𝖕𝖑𝖊 𝕻𝖗𝖊𝖔𝖗𝖉𝖊𝖗 𝕿𝖗𝖆𝖛𝖊𝖗𝖘𝖆𝖑 🚀💖
construct-string-from-binary-tree
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires constructing a string representation of a binary tree using the preorder traversal approach. The challenge is to omit unnecessary empty parenthesis pairs without affecting the one-to-one mapping relationship between t...
4
Given the `root` of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it. Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the original binary tree. **Example 1:** *...
null
【Video】Give me 7 minutes - Recursion and Stack solution(Bonus) - How we think about a solution
construct-string-from-binary-tree
1
1
# Intuition\nCheck right child first.\n\n---\n\n# Solution Video\n\nhttps://youtu.be/gV7MkiwMDS8\n\n\u25A0 Timeline of the video\n\n`0:05` How we create an output string\n`2:07` Coding\n`4:30` Time Complexity and Space Complexity\n`4:49` Step by step of recursion process\n`7:27` Step by step algorithm with my solution ...
56
Given the `root` of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it. Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the original binary tree. **Example 1:** *...
null
Python DFS recursion return f string directly
construct-string-from-binary-tree
0
1
# Intuition\nUse recursion. Instead of building the string by appending a list or using +=, we return the string directly in our recursive call using f strings.\n\n# Approach\nAt each recursive call, we assume that the next call "just works" and returns the correct answer. So when we are in the dfs call, we need to ask...
4
Given the `root` of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it. Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the original binary tree. **Example 1:** *...
null
Simple DFS code
construct-string-from-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<!-- 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 tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it. Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the original binary tree. **Example 1:** *...
null
Python3 Solution
construct-string-from-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 tree2str(self, root: Optional[TreeNode]) -> str:\n ans=[]\n def preorder(roo...
2
Given the `root` of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it. Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the original binary tree. **Example 1:** *...
null
✅ One Line Solution
construct-string-from-binary-tree
0
1
# Code #1.1 - Oneliner\nTime complexity: $$O(n^2)$$. Space complexity: $$O(n)$$.\nDisclaimer: this code is not a good example to use in a real project, it is written for fun mostly.\n```\nclass Solution:\n def tree2str(self, r: Optional[TreeNode]) -> str:\n return f\'{r.val}\' + (f\'({self.tree2str(r.left)})\...
1
Given the `root` of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it. Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the original binary tree. **Example 1:** *...
null
Solution
find-duplicate-file-in-system
1
1
```C++ []\nstruct trie {\n trie* content[75] {};\n vector<string> files;\n};\nclass Solution {\n trie root;\n void dfs(vector<vector<string>>& res, trie* node) {\n if(node->files.size() >= 2) {\n res.push_back(node->files);\n }\n for(int i = 0; i < 75; ++i) {\n if(...
1
Given a list `paths` of directory info, including the directory path, and all the files with contents in this directory, return _all the duplicate files in the file system in terms of their paths_. You may return the answer in **any order**. A group of duplicate files consists of at least two files that have the same ...
null
609: Time 95.76%, Solution with step by step explanation
find-duplicate-file-in-system
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Create a defaultdict object named "content_dict" that will store the file contents as keys and the file paths as values.\n2. Iterate over each path in the "paths" list.\n3. Split the path string into separate parts based ...
1
Given a list `paths` of directory info, including the directory path, and all the files with contents in this directory, return _all the duplicate files in the file system in terms of their paths_. You may return the answer in **any order**. A group of duplicate files consists of at least two files that have the same ...
null
🔥 [LeetCode The Hard Way] 🔥 Explained Line By Line
find-duplicate-file-in-system
0
1
Please check out [LeetCode The Hard Way](https://wingkwong.github.io/leetcode-the-hard-way/) for more solution explanations and tutorials. \nI\'ll explain my solution line by line daily and you can find the full list in my [Discord](https://discord.gg/Nqm4jJcyBf).\nIf you like it, please give a star, watch my [Github R...
28
Given a list `paths` of directory info, including the directory path, and all the files with contents in this directory, return _all the duplicate files in the file system in terms of their paths_. You may return the answer in **any order**. A group of duplicate files consists of at least two files that have the same ...
null
Easy python 10 lines solution using hashmap
find-duplicate-file-in-system
0
1
```\nfrom collections import defaultdict\nclass Solution:\n def findDuplicate(self, paths: List[str]) -> List[List[str]]:\n dic=defaultdict(lambda :[])\n for i in range(len(paths)):\n st=paths[i]\n lst=st.split(" ")\n for j in range(1,len(lst)):\n sp=lst[...
12
Given a list `paths` of directory info, including the directory path, and all the files with contents in this directory, return _all the duplicate files in the file system in terms of their paths_. You may return the answer in **any order**. A group of duplicate files consists of at least two files that have the same ...
null
Regex Solution Python [Easy]
find-duplicate-file-in-system
0
1
```\nimport re\n\nclass Solution:\n def findDuplicate(self, paths: List[str]) -> List[List[str]]:\n \n\t\t# this regex has two group: \n\t\t# 1. a file name group \n\t\t# 2. a content group\n\t\t#\n\t\t# Ex: "root/a 1.txt(abcd) 2.txt(efgh)"\n\t\t# \n\t\t# Output: [(\'1.txt\', \'abcd\'), (\'2.txt\', \'efgh\')]...
2
Given a list `paths` of directory info, including the directory path, and all the files with contents in this directory, return _all the duplicate files in the file system in terms of their paths_. You may return the answer in **any order**. A group of duplicate files consists of at least two files that have the same ...
null
[ Python ] ✅✅ Simple Python Solution Using Dictionary | HashMap🥳✌👍
find-duplicate-file-in-system
0
1
# If You like the Solution, Don\'t Forget To UpVote Me, Please UpVote! \uD83D\uDD3C\uD83D\uDE4F\n# Runtime: 175 ms, faster than 35.76% of Python3 online submissions for Find Duplicate File in System.\n# Memory Usage: 23.6 MB, less than 76.61% of Python3 online submissions for Find Duplicate File in System.\n\n\tclass S...
2
Given a list `paths` of directory info, including the directory path, and all the files with contents in this directory, return _all the duplicate files in the file system in terms of their paths_. You may return the answer in **any order**. A group of duplicate files consists of at least two files that have the same ...
null
Python || Dictionary || Easy Approach
find-duplicate-file-in-system
0
1
```\n\nclass Solution:\n def findDuplicate(self, paths: List[str]) -> List[List[str]]:\n contents = defaultdict(list)\n res = list()\n for direc in paths:\n d = direc.split()\n for i in range(1, len(d)):\n x = d[i].split("(")\n cont = x[1][:-1]...
1
Given a list `paths` of directory info, including the directory path, and all the files with contents in this directory, return _all the duplicate files in the file system in terms of their paths_. You may return the answer in **any order**. A group of duplicate files consists of at least two files that have the same ...
null
pythonic
find-duplicate-file-in-system
0
1
```\nclass Solution:\n def findDuplicate(self, paths: List[str]) -> List[List[str]]:\n data = defaultdict(list)\n for path in paths:\n directory, files = path.split(" ", 1)\n for file in files.split():\n file_content = file[file.index("("):-1]\n data[...
1
Given a list `paths` of directory info, including the directory path, and all the files with contents in this directory, return _all the duplicate files in the file system in terms of their paths_. You may return the answer in **any order**. A group of duplicate files consists of at least two files that have the same ...
null
pretty short python solution using hashmap
find-duplicate-file-in-system
0
1
```\nclass Solution:\n def findDuplicate(self, paths: List[str]) -> List[List[str]]:\n d=defaultdict(list)\n for i in paths:\n dirs=i.split()\n files=[dirs[k] for k in range(1,len(dirs))]\n for j in range(len(files)):\n val=files[j].split(\'(\')\n ...
1
Given a list `paths` of directory info, including the directory path, and all the files with contents in this directory, return _all the duplicate files in the file system in terms of their paths_. You may return the answer in **any order**. A group of duplicate files consists of at least two files that have the same ...
null
Solution
valid-triangle-number
1
1
```C++ []\ntypedef vector<int>::iterator vit;\nclass Solution {\npublic:\n int triangleNumber(vector<int>& nums) {\n if ( nums.size() < 3 ) return 0;\n vit b = nums.begin(), e = nums.end();\n sort(b, e);\n int res = 0;\n for ( vit k = b+2; k != e; ++k ){\n vit i = b, j =...
1
Given an integer array `nums`, return _the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle_. **Example 1:** **Input:** nums = \[2,2,3,4\] **Output:** 3 **Explanation:** Valid combinations are: 2,3,4 (using the first 2) 2,3,4 (using the second 2) 2,2,3 *...
null
Full Explanation + Python 2 line
valid-triangle-number
0
1
## Solution 1 :\n## What Q asked to do :\n```\nnums = [0,0,10,15,17,19,20,22,25,26,30,31,37] (sorted version)\n\nIf nums[i] is not 0 as with 0 length a triangle is not possible :\n_________________________________________________________________\n\nfor a triangle we need 3 length and if a+b>c and a+c>b and b+c>a BUT si...
2
Given an integer array `nums`, return _the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle_. **Example 1:** **Input:** nums = \[2,2,3,4\] **Output:** 3 **Explanation:** Valid combinations are: 2,3,4 (using the first 2) 2,3,4 (using the second 2) 2,2,3 *...
null
[Python3] | binary-search
valid-triangle-number
0
1
```\nclass Solution:\n def triangleNumber(self, nums: List[int]) -> int:\n n=len(nums)\n ans=0\n nums.sort()\n for i in range(n):\n for j in range(i+1,n):\n s2s=nums[i]+nums[j]\n ind=bisect.bisect_left(nums,s2s)\n ans+=max(0,ind-j-1)...
3
Given an integer array `nums`, return _the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle_. **Example 1:** **Input:** nums = \[2,2,3,4\] **Output:** 3 **Explanation:** Valid combinations are: 2,3,4 (using the first 2) 2,3,4 (using the second 2) 2,2,3 *...
null
611: Solution with step by step explanation
valid-triangle-number
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Sort the input array "nums" in ascending order.\n2. Initialize a variable "count" to 0, which will keep track of the number of valid triangles.\n3. Loop through all possible triplets in the array, using two pointers "i" a...
4
Given an integer array `nums`, return _the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle_. **Example 1:** **Input:** nums = \[2,2,3,4\] **Output:** 3 **Explanation:** Valid combinations are: 2,3,4 (using the first 2) 2,3,4 (using the second 2) 2,2,3 *...
null
Python Iterative solution
merge-two-binary-trees
0
1
\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)$$ -->\n\n# Code\n```\n\nclass Solution:\n def mergeTrees(self, root1: Optional[Tree...
2
You are given two binary trees `root1` and `root2`. Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new valu...
null
[Python] Simple Create New Tree By Joining Two Input Trees
merge-two-binary-trees
0
1
```\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 mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]...
20
You are given two binary trees `root1` and `root2`. Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new valu...
null
Python,Recursive Solution Beats 100%
merge-two-binary-trees
0
1
```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:\n if not t1:\n return t2\n elif not t...
54
You are given two binary trees `root1` and `root2`. Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new valu...
null
very easy solution 🔥🔥 || Python uwu
merge-two-binary-trees
0
1
\n```\nclass Solution:\n def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:\n if not root1:\n return root2\n if not root2:\n return root1\n\n root1.val += root2.val\n root1.left = self.mergeTrees(root1.left, root2.left)\...
3
You are given two binary trees `root1` and `root2`. Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new valu...
null
Python O(n) time, count it directly
task-scheduler
0
1
\n# Code\n```\nclass Solution:\n def leastInterval(self, tasks: List[str], n: int) -> int:\n cnt = [0] * 26\n for i in tasks: cnt[ord(i) - ord(\'A\')] += 1\n mx, mxcnt = max(cnt), 0\n for i in cnt: \n if i == mx: mxcnt += 1\n return max((mx - 1) * (n + 1) + mxcnt, len(ta...
12
Given a characters array `tasks`, representing the tasks a CPU needs to do, where each letter represents a different task. Tasks could be done in any order. Each task is done in one unit of time. For each unit of time, the CPU could complete either one task or just be idle. However, there is a non-negative integer `n`...
null
[Python] Very detailed explanation with examples
task-scheduler
0
1
```\nclass Solution:\n def leastInterval(self, tasks: List[str], n: int) -> int:\n ## RC ##\n ## APPROACH : HASHMAP ##\n ## LOGIC : TAKE THE MAXIMUM FREQUENCY ELEMENT AND MAKE THOSE MANY NUMBER OF SLOTS ##\n ## Slot size = (n+1) if n= 2 => slotsize = 3 Example: {A:5, B:1} => ABxAxxAxxAxx...
81
Given a characters array `tasks`, representing the tasks a CPU needs to do, where each letter represents a different task. Tasks could be done in any order. Each task is done in one unit of time. For each unit of time, the CPU could complete either one task or just be idle. However, there is a non-negative integer `n`...
null
Explanation of the Greedy Solution
task-scheduler
0
1
This is my explanation of the [Official Greedy Solution](https://leetcode.com/problems/task-scheduler/editorial/) \n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe arrange the task with the maximium occurence with a cooldown period of n. Then we insert the remaining tasks into the...
6
Given a characters array `tasks`, representing the tasks a CPU needs to do, where each letter represents a different task. Tasks could be done in any order. Each task is done in one unit of time. For each unit of time, the CPU could complete either one task or just be idle. However, there is a non-negative integer `n`...
null
Python | Heavily visualized + Detailed explanation
task-scheduler
0
1
I took some time to understand the logic behind it so I\'m sharing my understanding here with some graphs. Hopefully it would help you if are still confused.\n\nPlease upvote if you like.\n\nTaking ```tasks=[A,A,A,B,B,B,C,C,D,D],n=3``` as an example, we have a variable ```mx```: the maximum frequency of tasks. In this ...
52
Given a characters array `tasks`, representing the tasks a CPU needs to do, where each letter represents a different task. Tasks could be done in any order. Each task is done in one unit of time. For each unit of time, the CPU could complete either one task or just be idle. However, there is a non-negative integer `n`...
null
✔Beats 94.89% TC || Python Solution
design-circular-queue
0
1
# Code\n```\nclass MyCircularQueue:\n\n def __init__(self, k: int):\n self.queue = []\n self.k = k\n\n def enQueue(self, value: int) -> bool:\n if self.isFull():\n return False \n if len(self.queue) < self.k:\n self.queue.append(value)\n return True\n\n...
1
Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle, and the last position is connected back to the first position to make a circle. It is also called "Ring Buffer ". One of the benefits of th...
null
✔Beats 94.89% TC || Python Solution
design-circular-queue
0
1
# Code\n```\nclass MyCircularQueue:\n\n def __init__(self, k: int):\n self.queue = []\n self.k = k\n\n def enQueue(self, value: int) -> bool:\n if self.isFull():\n return False \n if len(self.queue) < self.k:\n self.queue.append(value)\n return True\n\n...
1
At a lemonade stand, each lemonade costs `$5`. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a `$5`, `$10`, or `$20` bill. You must provide the correct change to each customer so that the net tran...
null
Python || 99.49% Faster || Explained with comments
design-circular-queue
0
1
```\nclass MyCircularQueue:\n\n def __init__(self, k: int):\n self.size=k\n self.q=[0]*k\n self.front=-1\n self.rear=-1\n\n def enQueue(self, value: int) -> bool:\n if self.isFull():\n return False\n if self.isEmpty():\n self.front=self.rear=0\n ...
2
Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle, and the last position is connected back to the first position to make a circle. It is also called "Ring Buffer ". One of the benefits of th...
null
Python || 99.49% Faster || Explained with comments
design-circular-queue
0
1
```\nclass MyCircularQueue:\n\n def __init__(self, k: int):\n self.size=k\n self.q=[0]*k\n self.front=-1\n self.rear=-1\n\n def enQueue(self, value: int) -> bool:\n if self.isFull():\n return False\n if self.isEmpty():\n self.front=self.rear=0\n ...
2
At a lemonade stand, each lemonade costs `$5`. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a `$5`, `$10`, or `$20` bill. You must provide the correct change to each customer so that the net tran...
null
🔥 [LeetCode The Hard Way] 🔥 Explained Line By Line
design-circular-queue
1
1
Please check out [LeetCode The Hard Way](https://wingkwong.github.io/leetcode-the-hard-way/) for more solution explanations and tutorials. \nI\'ll explain my solution line by line daily and you can find the full list in my [Discord](https://discord.gg/Nqm4jJcyBf).\nIf you like it, please give a star, watch my [Github R...
90
Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle, and the last position is connected back to the first position to make a circle. It is also called "Ring Buffer ". One of the benefits of th...
null
🔥 [LeetCode The Hard Way] 🔥 Explained Line By Line
design-circular-queue
1
1
Please check out [LeetCode The Hard Way](https://wingkwong.github.io/leetcode-the-hard-way/) for more solution explanations and tutorials. \nI\'ll explain my solution line by line daily and you can find the full list in my [Discord](https://discord.gg/Nqm4jJcyBf).\nIf you like it, please give a star, watch my [Github R...
90
At a lemonade stand, each lemonade costs `$5`. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a `$5`, `$10`, or `$20` bill. You must provide the correct change to each customer so that the net tran...
null
✔️✔️✔️EASY Solution || Python
design-circular-queue
0
1
```\nclass MyCircularQueue:\n\n def __init__(self, k: int):\n self.q = []\n self.k = k\n def enQueue(self, value: int) -> bool:\n if not self.isFull():\n self.q.append(value)\n return True\n \n \n def deQueue(self) -> bool:\n if not self.isEmpty()...
5
Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle, and the last position is connected back to the first position to make a circle. It is also called "Ring Buffer ". One of the benefits of th...
null
✔️✔️✔️EASY Solution || Python
design-circular-queue
0
1
```\nclass MyCircularQueue:\n\n def __init__(self, k: int):\n self.q = []\n self.k = k\n def enQueue(self, value: int) -> bool:\n if not self.isFull():\n self.q.append(value)\n return True\n \n \n def deQueue(self) -> bool:\n if not self.isEmpty()...
5
At a lemonade stand, each lemonade costs `$5`. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a `$5`, `$10`, or `$20` bill. You must provide the correct change to each customer so that the net tran...
null
Python3 - Concise Readable Solution.
design-circular-queue
0
1
```\nclass MyCircularQueue:\n\n def __init__(self, k: int):\n self.queue = [-1] * k\n self.front = self.rear = -1\n self.size = 0 #current size of the queue\n self.maxsize = k #max size of the queue\n\n def enQueue(self, value: int) -> bool:\n if self.front == -1:\n ...
5
Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle, and the last position is connected back to the first position to make a circle. It is also called "Ring Buffer ". One of the benefits of th...
null
Python3 - Concise Readable Solution.
design-circular-queue
0
1
```\nclass MyCircularQueue:\n\n def __init__(self, k: int):\n self.queue = [-1] * k\n self.front = self.rear = -1\n self.size = 0 #current size of the queue\n self.maxsize = k #max size of the queue\n\n def enQueue(self, value: int) -> bool:\n if self.front == -1:\n ...
5
At a lemonade stand, each lemonade costs `$5`. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a `$5`, `$10`, or `$20` bill. You must provide the correct change to each customer so that the net tran...
null
Beats 99.98%|C++ Python
design-circular-queue
0
1
# Code C++\n```\nstruct Node {\n int val;\n Node* next;\n};\n\nclass MyCircularQueue {\nprivate:\n Node* last = nullptr;\n int maxSize = 0;\n int curSize = 0;\n\npublic:\n MyCircularQueue(int k) {\n maxSize = k;\n }\n\n bool enQueue(int value) {\n if (curSize == maxSize) {\n ...
1
Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle, and the last position is connected back to the first position to make a circle. It is also called "Ring Buffer ". One of the benefits of th...
null
Beats 99.98%|C++ Python
design-circular-queue
0
1
# Code C++\n```\nstruct Node {\n int val;\n Node* next;\n};\n\nclass MyCircularQueue {\nprivate:\n Node* last = nullptr;\n int maxSize = 0;\n int curSize = 0;\n\npublic:\n MyCircularQueue(int k) {\n maxSize = k;\n }\n\n bool enQueue(int value) {\n if (curSize == maxSize) {\n ...
1
At a lemonade stand, each lemonade costs `$5`. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a `$5`, `$10`, or `$20` bill. You must provide the correct change to each customer so that the net tran...
null
Python3 - AddOne method
design-circular-queue
0
1
\'\'\'\nclass MyCircularQueue:\n\n def __init__(self, k: int):\n self.data = [None] * (k + 1) # only k seats can be taken\n self.head = 1\n self.tail = 0\n self.MAX_SIZE = k + 1\n\n def enQueue(self, value: int) -> bool:\n if self.isFull(): return False\n self.tail = self...
1
Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle, and the last position is connected back to the first position to make a circle. It is also called "Ring Buffer ". One of the benefits of th...
null
Python3 - AddOne method
design-circular-queue
0
1
\'\'\'\nclass MyCircularQueue:\n\n def __init__(self, k: int):\n self.data = [None] * (k + 1) # only k seats can be taken\n self.head = 1\n self.tail = 0\n self.MAX_SIZE = k + 1\n\n def enQueue(self, value: int) -> bool:\n if self.isFull(): return False\n self.tail = self...
1
At a lemonade stand, each lemonade costs `$5`. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a `$5`, `$10`, or `$20` bill. You must provide the correct change to each customer so that the net tran...
null
✅ [Python] Simple, Clean 2 approach LinkedList & Array
design-circular-queue
0
1
### \u2714\uFE0F1. Using Linked-List\n\n```\n\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n \n\nclass MyCircularQueue:\n\n def __init__(self, k: int):\n self.k = k\n self.head = None\n self.counter = 0\n self.pointe...
1
Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle, and the last position is connected back to the first position to make a circle. It is also called "Ring Buffer ". One of the benefits of th...
null
✅ [Python] Simple, Clean 2 approach LinkedList & Array
design-circular-queue
0
1
### \u2714\uFE0F1. Using Linked-List\n\n```\n\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n \n\nclass MyCircularQueue:\n\n def __init__(self, k: int):\n self.k = k\n self.head = None\n self.counter = 0\n self.pointe...
1
At a lemonade stand, each lemonade costs `$5`. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a `$5`, `$10`, or `$20` bill. You must provide the correct change to each customer so that the net tran...
null
Solution
add-one-row-to-tree
1
1
```C++ []\nclass Solution {\npublic:\n TreeNode* addOneRow(TreeNode* root, int val, int depth) {\n if (depth == 1)\n return new TreeNode(val, root, NULL);\n if (!root) \n return NULL;\n\n root -> left = addOneRow(root -> left, val, depth - 1, true);\n root -> right =...
1
Given the `root` of a binary tree and two integers `val` and `depth`, add a row of nodes with value `val` at the given depth `depth`. Note that the `root` node is at depth `1`. The adding rule is: * Given the integer `depth`, for each not null tree node `cur` at the depth `depth - 1`, create two tree nodes with va...
null
623: Solution with step by step explanation
add-one-row-to-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Check if the depth is 1. If it is, create a new root node with value val, make its left subtree the original tree, and return the new root.\n2. Create a queue q and add a tuple containing the root node and its level (whic...
1
Given the `root` of a binary tree and two integers `val` and `depth`, add a row of nodes with value `val` at the given depth `depth`. Note that the `root` node is at depth `1`. The adding rule is: * Given the integer `depth`, for each not null tree node `cur` at the depth `depth - 1`, create two tree nodes with va...
null
✅ [Python] Simple Solutions Bfs [ 98%]
add-one-row-to-tree
0
1
Main idea:\n\nif at depth-1, we\'ll need children nodes of value val.\nIf the current node has a child, the child must be removed and made a child of the new node.\nIf the current node does not have a child, we can simply add the new node as a new node.\nif not at depth-1, go to the children and check if they are at de...
1
Given the `root` of a binary tree and two integers `val` and `depth`, add a row of nodes with value `val` at the given depth `depth`. Note that the `root` node is at depth `1`. The adding rule is: * Given the integer `depth`, for each not null tree node `cur` at the depth `depth - 1`, create two tree nodes with va...
null
Easy To Understand | 3 Lines 🚀🚀
maximum-product-of-three-numbers
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n Use this test case for better understanding --> [-100,-98,-1,2,3,4]\n\n# Complexity\n- Time complexity: O(NlogN)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space comple...
2
Given an integer array `nums`, _find three numbers whose product is maximum and return the maximum product_. **Example 1:** **Input:** nums = \[1,2,3\] **Output:** 6 **Example 2:** **Input:** nums = \[1,2,3,4\] **Output:** 24 **Example 3:** **Input:** nums = \[-1,-2,-3\] **Output:** -6 **Constraints:** * `3 <...
null
PYTHON SIMPLE
maximum-product-of-three-numbers
0
1
# Code\n```\nclass Solution:\n def maximumProduct(self, nums: List[int]) -> int:\n nums.sort(reverse = True)\n return max(nums[0] * nums[1] * nums[2], nums[0] * nums[-1] * nums[-2])\n \n```
1
Given an integer array `nums`, _find three numbers whose product is maximum and return the maximum product_. **Example 1:** **Input:** nums = \[1,2,3\] **Output:** 6 **Example 2:** **Input:** nums = \[1,2,3,4\] **Output:** 24 **Example 3:** **Input:** nums = \[-1,-2,-3\] **Output:** -6 **Constraints:** * `3 <...
null
easiest two lines of code#python3
maximum-product-of-three-numbers
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)$$ --...
17
Given an integer array `nums`, _find three numbers whose product is maximum and return the maximum product_. **Example 1:** **Input:** nums = \[1,2,3\] **Output:** 6 **Example 2:** **Input:** nums = \[1,2,3,4\] **Output:** 24 **Example 3:** **Input:** nums = \[-1,-2,-3\] **Output:** -6 **Constraints:** * `3 <...
null
[Python] O(N)
maximum-product-of-three-numbers
0
1
Time Complexcity O(N)\nSpace Complexcity O(1)\n```\nclass Solution:\n def maximumProduct(self, nums: List[int]) -> int:\n nums.sort()\n h3=nums[-1]*nums[-2]*nums[-3]\n l3=nums[0]*nums[1]*nums[-1]\n return max(h3,l3)\n \n```
1
Given an integer array `nums`, _find three numbers whose product is maximum and return the maximum product_. **Example 1:** **Input:** nums = \[1,2,3\] **Output:** 6 **Example 2:** **Input:** nums = \[1,2,3,4\] **Output:** 24 **Example 3:** **Input:** nums = \[-1,-2,-3\] **Output:** -6 **Constraints:** * `3 <...
null
Simple solution in python using sort
maximum-product-of-three-numbers
0
1
\n\n# Code\n```\nclass Solution:\n def maximumProduct(self, A: List[int]) -> int:\n A.sort()\n return max(A[0]*A[1]*A[-1], A[-1]*A[-2]*A[-3])\n```
3
Given an integer array `nums`, _find three numbers whose product is maximum and return the maximum product_. **Example 1:** **Input:** nums = \[1,2,3\] **Output:** 6 **Example 2:** **Input:** nums = \[1,2,3,4\] **Output:** 24 **Example 3:** **Input:** nums = \[-1,-2,-3\] **Output:** -6 **Constraints:** * `3 <...
null
2 Lines of Code-->Powerful Heap Concept
maximum-product-of-three-numbers
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)$$ --...
9
Given an integer array `nums`, _find three numbers whose product is maximum and return the maximum product_. **Example 1:** **Input:** nums = \[1,2,3\] **Output:** 6 **Example 2:** **Input:** nums = \[1,2,3,4\] **Output:** 24 **Example 3:** **Input:** nums = \[-1,-2,-3\] **Output:** -6 **Constraints:** * `3 <...
null
Python Easy Solution || Sorting
maximum-product-of-three-numbers
0
1
# Code\n```\nclass Solution:\n def maximumProduct(self, nums: List[int]) -> int:\n nums.sort()\n n=len(nums)\n return max(nums[n-1]*nums[n-2]*nums[n-3],nums[0]*nums[1]*nums[n-1])\n \n```
2
Given an integer array `nums`, _find three numbers whose product is maximum and return the maximum product_. **Example 1:** **Input:** nums = \[1,2,3\] **Output:** 6 **Example 2:** **Input:** nums = \[1,2,3,4\] **Output:** 24 **Example 3:** **Input:** nums = \[-1,-2,-3\] **Output:** -6 **Constraints:** * `3 <...
null
4 Lines of Python code
maximum-product-of-three-numbers
0
1
```\nclass Solution:\n def maximumProduct(self, nums: List[int]) -> int:\n nums.sort()\n l1 = nums[-1]*nums[-2]*nums[-3]\n l2 = nums[0]*nums[1]*nums[-1]\n return max(l1,l2)
4
Given an integer array `nums`, _find three numbers whose product is maximum and return the maximum product_. **Example 1:** **Input:** nums = \[1,2,3\] **Output:** 6 **Example 2:** **Input:** nums = \[1,2,3,4\] **Output:** 24 **Example 3:** **Input:** nums = \[-1,-2,-3\] **Output:** -6 **Constraints:** * `3 <...
null
Solution
maximum-product-of-three-numbers
1
1
```C++ []\nclass Solution {\npublic:\n int maximumProduct(vector<int>& nums) {\n int max1 = INT32_MIN, max2 = INT32_MIN, max3 = INT32_MIN;\n int min1 = INT32_MAX, min2 = INT32_MAX;\n for(int& num : nums) {\n if(num > max1) {\n max3 = max2, max2 = max1, max1 = num;\n ...
3
Given an integer array `nums`, _find three numbers whose product is maximum and return the maximum product_. **Example 1:** **Input:** nums = \[1,2,3\] **Output:** 6 **Example 2:** **Input:** nums = \[1,2,3,4\] **Output:** 24 **Example 3:** **Input:** nums = \[-1,-2,-3\] **Output:** -6 **Constraints:** * `3 <...
null
Superb Logic in java and Python(Heap concept)
maximum-product-of-three-numbers
1
1
\n\n# Superb Solution in JAVA\n```\nclass Solution {\n public int maximumProduct(int[] nums) {\n Arrays.sort(nums);\n int n=nums.length;\n return Math.max(nums[0]*nums[1]*nums[n-1],nums[n-1]*nums[n-2]*nums[n-3]); \n }\n}\n```\n# Excellent Solution in Python Using Heap Concept\n```\nclass Solution:...
4
Given an integer array `nums`, _find three numbers whose product is maximum and return the maximum product_. **Example 1:** **Input:** nums = \[1,2,3\] **Output:** 6 **Example 2:** **Input:** nums = \[1,2,3,4\] **Output:** 24 **Example 3:** **Input:** nums = \[-1,-2,-3\] **Output:** -6 **Constraints:** * `3 <...
null
python 2 liner code faster
maximum-product-of-three-numbers
0
1
```\n def maximumProduct(self, nums: List[int]) -> int:\n nums.sort()\n return max((nums[-1]*nums[-2]*nums[-3]),(nums[0]*nums[1]*nums[-1]))\n```
3
Given an integer array `nums`, _find three numbers whose product is maximum and return the maximum product_. **Example 1:** **Input:** nums = \[1,2,3\] **Output:** 6 **Example 2:** **Input:** nums = \[1,2,3,4\] **Output:** 24 **Example 3:** **Input:** nums = \[-1,-2,-3\] **Output:** -6 **Constraints:** * `3 <...
null
Solution
k-inverse-pairs-array
1
1
```C++ []\nconstexpr long MODULUS = 1\'000\'000\'007;\n\nstatic int ANSWERS[1001][1001] = {};\nstatic bool CALCULATED = false;\n\nclass Solution {\npublic:\n int kInversePairs(int in_n, int in_k) {\n if (CALCULATED) {\n return ANSWERS[in_n][in_k];\n }\n for (int n = 1; n <= 1000; n++)...
1
For an integer array `nums`, an **inverse pair** is a pair of integers `[i, j]` where `0 <= i < j < nums.length` and `nums[i] > nums[j]`. Given two integers n and k, return the number of different arrays consist of numbers from `1` to `n` such that there are exactly `k` **inverse pairs**. Since the answer can be huge,...
null
Easy Solution || Beats 99% || Python
k-inverse-pairs-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
For an integer array `nums`, an **inverse pair** is a pair of integers `[i, j]` where `0 <= i < j < nums.length` and `nums[i] > nums[j]`. Given two integers n and k, return the number of different arrays consist of numbers from `1` to `n` such that there are exactly `k` **inverse pairs**. Since the answer can be huge,...
null
Python3 || dp,1D array, 10 lines, w/ explanation || T/M: 95%/86%
k-inverse-pairs-array
0
1
```\nclass Solution:\n # A very good description of the dp solution is at\n # https://leetcode.com/problems/k-inverse-pairs-array/solution/ \n # The code below uses two 1D arrays--dp and tmp--instead if a \n # 2D array. tmp repl...
8
For an integer array `nums`, an **inverse pair** is a pair of integers `[i, j]` where `0 <= i < j < nums.length` and `nums[i] > nums[j]`. Given two integers n and k, return the number of different arrays consist of numbers from `1` to `n` such that there are exactly `k` **inverse pairs**. Since the answer can be huge,...
null
PYTHON 95% FASTER EASY BEGINER FRIENDLY Multiple Solutions
k-inverse-pairs-array
0
1
# DON\'T FORGET TO UPVOTE.\n\n# 1. 95% Faster solution:\n\n\n\t\tclass Solution:\n\t\t\tdef kInversePairs(self, n: int, k: int) -> int:\n\t\t\t\tm = 10 ** 9 + 7\n\n\t\t\t\tdp0 = [0] * (k + 1)\n\t\t\t\tdp0[0] = 1\n\n\t\t\t\tfor i in range(n):\n\t\t\t\t\tdp1 = []\n\t\t\t\t\ts = 0\n\t\t\t\t\tfor j in range(k + 1):\n\t\t\t...
5
For an integer array `nums`, an **inverse pair** is a pair of integers `[i, j]` where `0 <= i < j < nums.length` and `nums[i] > nums[j]`. Given two integers n and k, return the number of different arrays consist of numbers from `1` to `n` such that there are exactly `k` **inverse pairs**. Since the answer can be huge,...
null
Python3 || Heapq || Faster Solution with explanation
course-schedule-iii
0
1
We start learning courses with earliest closing date first. If we find a course that can\'t fit into its close date, we can un-learn one of the previous course in order to fit it in. We can safely un-learn a previous course because it closes earlier and there is no way for it to be picked up again later. We pick up the...
33
There are `n` different online courses numbered from `1` to `n`. You are given an array `courses` where `courses[i] = [durationi, lastDayi]` indicate that the `ith` course should be taken **continuously** for `durationi` days and must be finished before or on `lastDayi`. You will start on the `1st` day and you cannot ...
During iteration, say I want to add the current course, currentTotalTime being total time of all courses taken till now, but adding the current course might exceed my deadline or it doesn’t. 1. If it doesn’t, then I have added one new course. Increment the currentTotalTime with duration of current course. 2. If it e...
Python3 || Heapq || Faster Solution with explanation
course-schedule-iii
0
1
We start learning courses with earliest closing date first. If we find a course that can\'t fit into its close date, we can un-learn one of the previous course in order to fit it in. We can safely un-learn a previous course because it closes earlier and there is no way for it to be picked up again later. We pick up the...
33
There are `n` different online courses numbered from `1` to `n`. You are given an array `courses` where `courses[i] = [durationi, lastDayi]` indicate that the `ith` course should be taken **continuously** for `durationi` days and must be finished before or on `lastDayi`. You will start on the `1st` day and you cannot ...
During iteration, say I want to add the current course, currentTotalTime being total time of all courses taken till now, but adding the current course might exceed my deadline or it doesn’t. 1. If it doesn’t, then I have added one new course. Increment the currentTotalTime with duration of current course. 2. If it exc...
Python Max Heap O(NlogN) very straighforward and explained well
course-schedule-iii
0
1
Solution Explanation: \n Intuition: Move forward till you can and when you can\'t move leave out something from behind that will optimize the current state. Dropping a longer duration course that we took before and taking in a shorter duration will optimize our current state. Reason is because it will leave more roo...
4
There are `n` different online courses numbered from `1` to `n`. You are given an array `courses` where `courses[i] = [durationi, lastDayi]` indicate that the `ith` course should be taken **continuously** for `durationi` days and must be finished before or on `lastDayi`. You will start on the `1st` day and you cannot ...
During iteration, say I want to add the current course, currentTotalTime being total time of all courses taken till now, but adding the current course might exceed my deadline or it doesn’t. 1. If it doesn’t, then I have added one new course. Increment the currentTotalTime with duration of current course. 2. If it e...
Python Max Heap O(NlogN) very straighforward and explained well
course-schedule-iii
0
1
Solution Explanation: \n Intuition: Move forward till you can and when you can\'t move leave out something from behind that will optimize the current state. Dropping a longer duration course that we took before and taking in a shorter duration will optimize our current state. Reason is because it will leave more roo...
4
There are `n` different online courses numbered from `1` to `n`. You are given an array `courses` where `courses[i] = [durationi, lastDayi]` indicate that the `ith` course should be taken **continuously** for `durationi` days and must be finished before or on `lastDayi`. You will start on the `1st` day and you cannot ...
During iteration, say I want to add the current course, currentTotalTime being total time of all courses taken till now, but adding the current course might exceed my deadline or it doesn’t. 1. If it doesn’t, then I have added one new course. Increment the currentTotalTime with duration of current course. 2. If it exc...
Python Recursive + Memoization + Bottom-UP - Greedy + Heap
course-schedule-iii
0
1
Typical Knapsack Problem, either take the course or not, calculate total number of days by taking course and choose the maximum number of courses taken at that point of time.\n***Recursion: Time Limit Exceeded***\n```\nclass Solution:\n def scheduleCourse(self, courses: List[List[int]]) -> int:\n # First, sor...
3
There are `n` different online courses numbered from `1` to `n`. You are given an array `courses` where `courses[i] = [durationi, lastDayi]` indicate that the `ith` course should be taken **continuously** for `durationi` days and must be finished before or on `lastDayi`. You will start on the `1st` day and you cannot ...
During iteration, say I want to add the current course, currentTotalTime being total time of all courses taken till now, but adding the current course might exceed my deadline or it doesn’t. 1. If it doesn’t, then I have added one new course. Increment the currentTotalTime with duration of current course. 2. If it e...
Python Recursive + Memoization + Bottom-UP - Greedy + Heap
course-schedule-iii
0
1
Typical Knapsack Problem, either take the course or not, calculate total number of days by taking course and choose the maximum number of courses taken at that point of time.\n***Recursion: Time Limit Exceeded***\n```\nclass Solution:\n def scheduleCourse(self, courses: List[List[int]]) -> int:\n # First, sor...
3
There are `n` different online courses numbered from `1` to `n`. You are given an array `courses` where `courses[i] = [durationi, lastDayi]` indicate that the `ith` course should be taken **continuously** for `durationi` days and must be finished before or on `lastDayi`. You will start on the `1st` day and you cannot ...
During iteration, say I want to add the current course, currentTotalTime being total time of all courses taken till now, but adding the current course might exceed my deadline or it doesn’t. 1. If it doesn’t, then I have added one new course. Increment the currentTotalTime with duration of current course. 2. If it exc...
Solution
smallest-range-covering-elements-from-k-lists
1
1
```C++ []\nclass Solution {\npublic:\n std::vector<int> smallestRange(std::vector<std::vector<int>> const &nums)\n {\n auto S = nums.size();\n std::vector<std::pair<std::vector<int>::const_iterator,\n std::vector<int>::const_iterator>>\n ps(S);\n std::transform(nums.begin(),\n...
1
You have `k` lists of sorted integers in **non-decreasing order**. Find the **smallest** range that includes at least one number from each of the `k` lists. We define the range `[a, b]` is smaller than range `[c, d]` if `b - a < d - c` **or** `a < c` if `b - a == d - c`. **Example 1:** **Input:** nums = \[\[4,10,15,...
null
Very inituive solution with sorting.
smallest-range-covering-elements-from-k-lists
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe leverage the requirement that range has to include at least one number. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nIf we get a sorted list that contains every numbers from each k list, we only need to keep...
0
You have `k` lists of sorted integers in **non-decreasing order**. Find the **smallest** range that includes at least one number from each of the `k` lists. We define the range `[a, b]` is smaller than range `[c, d]` if `b - a < d - c` **or** `a < c` if `b - a == d - c`. **Example 1:** **Input:** nums = \[\[4,10,15,...
null
Using min heap to get min of current nums and tracking a max val to enumerate valid ranges
smallest-range-covering-elements-from-k-lists
0
1
# Code\n```\nclass Solution:\n # T = O(Nlog(K)) for the heap popping happening n times \n # S = O(K) for the heap\n def smallestRange(self, nums: List[List[int]]) -> List[int]:\n ans = -math.inf, math.inf # max range to start with\n\n heap = []\n \n high = -math.inf\n # track...
1
You have `k` lists of sorted integers in **non-decreasing order**. Find the **smallest** range that includes at least one number from each of the `k` lists. We define the range `[a, b]` is smaller than range `[c, d]` if `b - a < d - c` **or** `a < c` if `b - a == d - c`. **Example 1:** **Input:** nums = \[\[4,10,15,...
null
Awesome Logic With Heap Concept
smallest-range-covering-elements-from-k-lists
0
1
# Using Heap Concept:\n```\nclass Solution:\n def smallestRange(self, nums: List[List[int]]) -> List[int]:\n heap=[]\n maxvalue=0\n for i in range(len(nums)):\n heapq.heappush(heap,[nums[i][0],i,0])\n maxvalue=max(maxvalue,nums[i][0])\n answer=[heap[0][0],maxvalue]\n...
9
You have `k` lists of sorted integers in **non-decreasing order**. Find the **smallest** range that includes at least one number from each of the `k` lists. We define the range `[a, b]` is smaller than range `[c, d]` if `b - a < d - c` **or** `a < c` if `b - a == d - c`. **Example 1:** **Input:** nums = \[\[4,10,15,...
null
python using heap |
smallest-range-covering-elements-from-k-lists
0
1
```\nclass Solution:\n def smallestRange(self, nums: List[List[int]]) -> List[int]:\n \n n = len(nums)\n \n pq = []\n ma = 0\n \n for i in range(n):\n \n heappush(pq, (nums[i][0] , i, 0))\n ma = max(ma , nums[i][0])\n \n ...
18
You have `k` lists of sorted integers in **non-decreasing order**. Find the **smallest** range that includes at least one number from each of the `k` lists. We define the range `[a, b]` is smaller than range `[c, d]` if `b - a < d - c` **or** `a < c` if `b - a == d - c`. **Example 1:** **Input:** nums = \[\[4,10,15,...
null
Solution
sum-of-square-numbers
1
1
```C++ []\nclass Solution {\npublic:\n bool judgeSquareSum(int c) {\n if(c==1)\n return true;\n long long int left=0, right = sqrt(c);\n while(left<=right){\n long long int sum = (left*left) + (right*right);\n if(sum==c)\n return true;\n e...
3
Given a non-negative integer `c`, decide whether there're two integers `a` and `b` such that `a2 + b2 = c`. **Example 1:** **Input:** c = 5 **Output:** true **Explanation:** 1 \* 1 + 2 \* 2 = 5 **Example 2:** **Input:** c = 3 **Output:** false **Constraints:** * `0 <= c <= 231 - 1`
null
Easy python solution using binary Search || 2 different Solution using BS
sum-of-square-numbers
0
1
# #Solution 1\n![image.png](https://assets.leetcode.com/users/images/6e67f58e-4c7a-4c6c-b444-438967201ed4_1679075137.5026033.png)\n\n# Code\n```\nclass Solution:\n def judgeSquareSum(self, c: int) -> bool:\n i=0\n j=int(c**(1/2))\n while i<=j:\n m=i*i+j*j\n if m==c:\n ...
3
Given a non-negative integer `c`, decide whether there're two integers `a` and `b` such that `a2 + b2 = c`. **Example 1:** **Input:** c = 5 **Output:** true **Explanation:** 1 \* 1 + 2 \* 2 = 5 **Example 2:** **Input:** c = 3 **Output:** false **Constraints:** * `0 <= c <= 231 - 1`
null
Python3 Easy Solution |One Pointer | faster thar 91%
sum-of-square-numbers
0
1
\n\n\n```\n for a in range(int(sqrt(c))+1):\n b=sqrt(c-a*a)\n if b==int(b): return True\n```\n![image](https://assets.leetcode.com/users/images/a84dd7af-6137-4248-bd46-c5e89e4e99d2_1667313113.9619918.png)
4
Given a non-negative integer `c`, decide whether there're two integers `a` and `b` such that `a2 + b2 = c`. **Example 1:** **Input:** c = 5 **Output:** true **Explanation:** 1 \* 1 + 2 \* 2 = 5 **Example 2:** **Input:** c = 3 **Output:** false **Constraints:** * `0 <= c <= 231 - 1`
null
Binary Search and Two Pointers Approach----->Python3
sum-of-square-numbers
0
1
# 1. Two Pointers Approach\n``` \nclass Solution:\n def judgeSquareSum(self, c: int) -> bool:\n i,j=0,int(sqrt(c))\n while i<=j:\n if i*i+j*j==c:\n return True\n if i*i+j*j>c:\n j-=1\n else:\n i+=1\n return False\n```\...
5
Given a non-negative integer `c`, decide whether there're two integers `a` and `b` such that `a2 + b2 = c`. **Example 1:** **Input:** c = 5 **Output:** true **Explanation:** 1 \* 1 + 2 \* 2 = 5 **Example 2:** **Input:** c = 3 **Output:** false **Constraints:** * `0 <= c <= 231 - 1`
null
633: Solution with step by step explanation
sum-of-square-numbers
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Initialize left and right pointers to 0 and the integer square root of c respectively.\n2. While the left pointer is less than or equal to the right pointer, compute the current sum of squares.\n3. If the current sum is e...
1
Given a non-negative integer `c`, decide whether there're two integers `a` and `b` such that `a2 + b2 = c`. **Example 1:** **Input:** c = 5 **Output:** true **Explanation:** 1 \* 1 + 2 \* 2 = 5 **Example 2:** **Input:** c = 3 **Output:** false **Constraints:** * `0 <= c <= 231 - 1`
null
[Python][Stack]Easy to Understand]
exclusive-time-of-functions
0
1
In this solution, we calculate the time in place rather than waiting for the **endtime** of the process. \n\nWe always keep track of current time **currt**\n\n\nWhenever a new process is started, we calculate the time taken by the previus process till now ( **timestamp -currt**) and and add that to the stack along with...
3
On a **single-threaded** CPU, we execute a program containing `n` functions. Each function has a unique ID between `0` and `n-1`. Function calls are **stored in a [call stack](https://en.wikipedia.org/wiki/Call_stack)**: when a function call starts, its ID is pushed onto the stack, and when a function call ends, its I...
null
Python 3 || 12 lines, stack, w/example || T/M: 95% / 94%
exclusive-time-of-functions
0
1
```\nclass Solution:\n def exclusiveTime(self, n: int, logs: List[str]) -> List[int]:\n\n stack, ans = deque(), [0]*n # Example: ["0:start:0", "0:start:2", "0:end:5",\n # "1:start:6", "1:end :6", "0:end:7"]\n \n ...
6
On a **single-threaded** CPU, we execute a program containing `n` functions. Each function has a unique ID between `0` and `n-1`. Function calls are **stored in a [call stack](https://en.wikipedia.org/wiki/Call_stack)**: when a function call starts, its ID is pushed onto the stack, and when a function call ends, its I...
null