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
Unleashing the Power of Dynamic Programming
concatenated-words
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- To check if a word can be formed by concatenating other words from the input list, we can use dynamic programming.\n- We will use a boolean array dp where dp[i] will be True if a word can be formed from the substring word[0:i].\n- We wi...
1
Given an array of strings `words` (**without duplicates**), return _all the **concatenated words** in the given list of_ `words`. A **concatenated word** is defined as a string that is comprised entirely of at least two shorter words (not necesssarily distinct) in the given array. **Example 1:** **Input:** words = \...
null
Clean Codes🔥🔥|| Full Explanation✅|| Trie & DFS✅|| C++|| Java || Python3
concatenated-words
1
1
# Intuition :\n- We can use the data structure trie to store the words. Then for each word in the list of words, we use depth first search to see whether it is a concatenation of two or more words from the list.\n\n- We first build a trie structure that stores the list of words. In every trie node, we use an array of l...
38
Given an array of strings `words` (**without duplicates**), return _all the **concatenated words** in the given list of_ `words`. A **concatenated word** is defined as a string that is comprised entirely of at least two shorter words (not necesssarily distinct) in the given array. **Example 1:** **Input:** words = \...
null
📌📌Python3 || ⚡347 ms, faster than 91.39% of Python3
concatenated-words
0
1
```\ndef findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]:\n wordset = set(words)\n result = []\n def dfs(word, wordset):\n if word == "":\n return True\n for i in range(len(word)):\n if word[:i+1] in wordset:\n ...
4
Given an array of strings `words` (**without duplicates**), return _all the **concatenated words** in the given list of_ `words`. A **concatenated word** is defined as a string that is comprised entirely of at least two shorter words (not necesssarily distinct) in the given array. **Example 1:** **Input:** words = \...
null
python3 Solution
concatenated-words
0
1
\n```\nclass Solution:\n def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]:\n wordset = set(words)\n \n @cache\n def f(word,i):\n if i >= len(word):\n return True\n j = i+1\n while j <= len(word):\n if w...
1
Given an array of strings `words` (**without duplicates**), return _all the **concatenated words** in the given list of_ `words`. A **concatenated word** is defined as a string that is comprised entirely of at least two shorter words (not necesssarily distinct) in the given array. **Example 1:** **Input:** words = \...
null
O(N*L) | O(N*L) | Python Solution | Explained
concatenated-words
0
1
Hello **Tenno Leetcoders**, \n\nFor this problem, we want to return all non duplicated `concatenated words`\n\nThis problem has the same logic as `139. Word Break`. This problem has its differences though because we want only words that are concatenated by 2 or more other words\n\nWe can use `Dynamic Programming` to b...
4
Given an array of strings `words` (**without duplicates**), return _all the **concatenated words** in the given list of_ `words`. A **concatenated word** is defined as a string that is comprised entirely of at least two shorter words (not necesssarily distinct) in the given array. **Example 1:** **Input:** words = \...
null
💡💡 Neatly coded and brilliantly structured backtracking solution
matchsticks-to-square
0
1
# Intuition behind the approach\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe use backtracking to get the different combinations with a few overheads before backtracking so that the runtime does not exceed the limit.\nWe sort the array in reverse order so that if any matchstick is greater tha...
1
You are given an integer array `matchsticks` where `matchsticks[i]` is the length of the `ith` matchstick. You want to use **all the matchsticks** to make one square. You **should not break** any stick, but you can link them up, and each matchstick must be used **exactly one time**. Return `true` if you can make this ...
Treat the matchsticks as an array. Can we split the array into 4 equal halves? Every matchstick can belong to either of the 4 sides. We don't know which one. Maybe try out all options! For every matchstick, we have to try out each of the 4 options i.e. which side it can belong to. We can make use of recursion for this....
[Python 3]DP + Bitmask
matchsticks-to-square
0
1
```\nclass Solution:\n def makesquare(self, arr: List[int]) -> bool:\n\t\t# no way to make the square if total length not divisble by 4\n if sum(arr) % 4:\n return False\n \n\t\t# target side length\n side = sum(arr) // 4\n \n @lru_cache(None)\n def dp(k, mask, s)...
6
You are given an integer array `matchsticks` where `matchsticks[i]` is the length of the `ith` matchstick. You want to use **all the matchsticks** to make one square. You **should not break** any stick, but you can link them up, and each matchstick must be used **exactly one time**. Return `true` if you can make this ...
Treat the matchsticks as an array. Can we split the array into 4 equal halves? Every matchstick can belong to either of the 4 sides. We don't know which one. Maybe try out all options! For every matchstick, we have to try out each of the 4 options i.e. which side it can belong to. We can make use of recursion for this....
Cleanest Python3 code with explanation / Generalized partitioning into k-buckets
matchsticks-to-square
0
1
### Breakdown\n1. Few basic checks are needed \u2013\xA0there should be at least 4 matchsticks, the sum of matchstick lengths should be divisble by 4, and none of the matchstick length should exceed the side length of the square.\n2. To partition a list of nums (matchsticks) into k-buckets (4 sides in our case), we use...
2
You are given an integer array `matchsticks` where `matchsticks[i]` is the length of the `ith` matchstick. You want to use **all the matchsticks** to make one square. You **should not break** any stick, but you can link them up, and each matchstick must be used **exactly one time**. Return `true` if you can make this ...
Treat the matchsticks as an array. Can we split the array into 4 equal halves? Every matchstick can belong to either of the 4 sides. We don't know which one. Maybe try out all options! For every matchstick, we have to try out each of the 4 options i.e. which side it can belong to. We can make use of recursion for this....
Python | 380ms Faster than 78% | Soln w/ Explanation | 86% Less Memory
matchsticks-to-square
0
1
```\ndef makesquare(self, matchsticks: List[int]) -> bool:\n\ttotal = sum(matchsticks)\n\n\tif total % 4: # if total isn\'t perfectly divisible by 4 then we can\'t make a square\n\t\treturn False\n\n\treqLen = total // 4 # calculate length of each side we require\n\tsides = [0] * 4\n\tmatchsticks.sort(reverse = True) #...
13
You are given an integer array `matchsticks` where `matchsticks[i]` is the length of the `ith` matchstick. You want to use **all the matchsticks** to make one square. You **should not break** any stick, but you can link them up, and each matchstick must be used **exactly one time**. Return `true` if you can make this ...
Treat the matchsticks as an array. Can we split the array into 4 equal halves? Every matchstick can belong to either of the 4 sides. We don't know which one. Maybe try out all options! For every matchstick, we have to try out each of the 4 options i.e. which side it can belong to. We can make use of recursion for this....
473: Solution with step by step explanation
matchsticks-to-square
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Calculate the total length of all matchsticks in the input list matchsticks.\n2. If the total length is not divisible by 4 or if the length of the longest matchstick is greater than total_length // 4, return False as it\'...
4
You are given an integer array `matchsticks` where `matchsticks[i]` is the length of the `ith` matchstick. You want to use **all the matchsticks** to make one square. You **should not break** any stick, but you can link them up, and each matchstick must be used **exactly one time**. Return `true` if you can make this ...
Treat the matchsticks as an array. Can we split the array into 4 equal halves? Every matchstick can belong to either of the 4 sides. We don't know which one. Maybe try out all options! For every matchstick, we have to try out each of the 4 options i.e. which side it can belong to. We can make use of recursion for this....
python | using Backtracking | Faster than 99%
matchsticks-to-square
0
1
```\nclass Solution:\n def makesquare(self, matchsticks: List[int]) -> bool:\n target,m=divmod(sum(matchsticks),4)\n if m:return False\n targetLst=[0]*4\n length=len(matchsticks)\n matchsticks.sort(reverse=True)\n def bt(i):\n if i==length:\n return...
1
You are given an integer array `matchsticks` where `matchsticks[i]` is the length of the `ith` matchstick. You want to use **all the matchsticks** to make one square. You **should not break** any stick, but you can link them up, and each matchstick must be used **exactly one time**. Return `true` if you can make this ...
Treat the matchsticks as an array. Can we split the array into 4 equal halves? Every matchstick can belong to either of the 4 sides. We don't know which one. Maybe try out all options! For every matchstick, we have to try out each of the 4 options i.e. which side it can belong to. We can make use of recursion for this....
Python Backtracking
matchsticks-to-square
0
1
```\nclass Solution:\n def makesquare(self, matchsticks: List[int]) -> bool:\n \n \n sides = [0]*4\n if sum(matchsticks)%4!=0:\n return False\n s = sum(matchsticks)//4\n \n matchsticks.sort(reverse=True)\n \n def helper(i):\n if i =...
1
You are given an integer array `matchsticks` where `matchsticks[i]` is the length of the `ith` matchstick. You want to use **all the matchsticks** to make one square. You **should not break** any stick, but you can link them up, and each matchstick must be used **exactly one time**. Return `true` if you can make this ...
Treat the matchsticks as an array. Can we split the array into 4 equal halves? Every matchstick can belong to either of the 4 sides. We don't know which one. Maybe try out all options! For every matchstick, we have to try out each of the 4 options i.e. which side it can belong to. We can make use of recursion for this....
Python Easy DP 2 approaches
ones-and-zeroes
0
1
\n1. ##### **Memoization(Top Down)**\n\n```\nclass Solution:\n def findMaxForm(self, strs: List[str], m: int, n: int) -> int:\n counter=[[s.count("0"), s.count("1")] for s in strs]\n \n @cache\n def dp(i,j,idx):\n if i<0 or j<0:\n return -math.inf\n \n...
83
You are given an array of binary strings `strs` and two integers `m` and `n`. Return _the size of the largest subset of `strs` such that there are **at most**_ `m` `0`_'s and_ `n` `1`_'s in the subset_. A set `x` is a **subset** of a set `y` if all elements of `x` are also elements of `y`. **Example 1:** **Input:**...
null
beat 99.9%, extremely fast
ones-and-zeroes
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCounter to count \'0\' and \'1\' size\n# Approach\n<!-- Describe your approach to solving the problem. -->\nDP\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your ...
1
You are given an array of binary strings `strs` and two integers `m` and `n`. Return _the size of the largest subset of `strs` such that there are **at most**_ `m` `0`_'s and_ `n` `1`_'s in the subset_. A set `x` is a **subset** of a set `y` if all elements of `x` are also elements of `y`. **Example 1:** **Input:**...
null
[Python] DP Solution explained with example
ones-and-zeroes
0
1
```\nclass Solution:\n def findMaxForm(self, strs: List[str], m: int, n: int) -> int:\n ## RC ##\n\t\t## APPROACH : DP ##\n\t\t## Similar to Leetcode 416. partition equal subset sum ##\n\t\t## LOGIC ##\n\t\t#\t1. This problem can be decomposed to 0/1 Knapsack Problem, where you have n items with each having i...
47
You are given an array of binary strings `strs` and two integers `m` and `n`. Return _the size of the largest subset of `strs` such that there are **at most**_ `m` `0`_'s and_ `n` `1`_'s in the subset_. A set `x` is a **subset** of a set `y` if all elements of `x` are also elements of `y`. **Example 1:** **Input:**...
null
Python || Easy Recursion || DP
ones-and-zeroes
0
1
```\nclass Solution(object):\n def findMaxForm(self, strs, m, n):\n """\n :type strs: List[str]\n :type m: int\n :type n: int\n :rtype: int\n """\n #dp dict to store the computations\n dp={}\n \n \n def A(curm,curn,ind):\n \n ...
2
You are given an array of binary strings `strs` and two integers `m` and `n`. Return _the size of the largest subset of `strs` such that there are **at most**_ `m` `0`_'s and_ `n` `1`_'s in the subset_. A set `x` is a **subset** of a set `y` if all elements of `x` are also elements of `y`. **Example 1:** **Input:**...
null
Accepted Greedy Solution with Counterexample
ones-and-zeroes
0
1
# Overview\nGreedily take strings based on some sorted order. 4 orders were examined: sorting by (# of 0\'s, # of 1\'s), sorting by (# of 1\'s, # of 0\'s), sorting (combined length, # of 0\'s, # of 1\'s), (combined length, # of 1\'s, # of 0\'s).\n\n# Code\n```\nclass Solution:\n def findMaxForm(self, strs: List[str]...
3
You are given an array of binary strings `strs` and two integers `m` and `n`. Return _the size of the largest subset of `strs` such that there are **at most**_ `m` `0`_'s and_ `n` `1`_'s in the subset_. A set `x` is a **subset** of a set `y` if all elements of `x` are also elements of `y`. **Example 1:** **Input:**...
null
✔ Python3 Solution | Knapsack | DP
ones-and-zeroes
0
1
# Complexity\n- Time complexity: $$O(n * m * s.length)$$\n- Space complexity: $$O(n * m)$$\n\n# Code\n```Python\nclass Solution:\n def findMaxForm(self, S, M, N):\n dp = [[0] * (M + 1) for _ in range(N + 1)]\n for s in S:\n x, y = s.count(\'1\'), s.count(\'0\')\n for i in range(N ...
3
You are given an array of binary strings `strs` and two integers `m` and `n`. Return _the size of the largest subset of `strs` such that there are **at most**_ `m` `0`_'s and_ `n` `1`_'s in the subset_. A set `x` is a **subset** of a set `y` if all elements of `x` are also elements of `y`. **Example 1:** **Input:**...
null
474: Solution with step by step explanation
ones-and-zeroes
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Initialize a 2D array, dp, with m+1 rows and n+1 columns, filled with 0\'s. The purpose of this array is to keep track of the maximum subset size for each combination of zeros and ones that can be formed with the current ...
5
You are given an array of binary strings `strs` and two integers `m` and `n`. Return _the size of the largest subset of `strs` such that there are **at most**_ `m` `0`_'s and_ `n` `1`_'s in the subset_. A set `x` is a **subset** of a set `y` if all elements of `x` are also elements of `y`. **Example 1:** **Input:**...
null
Python | Easy DP
ones-and-zeroes
0
1
```\nclass Solution:\n def findMaxForm(self, strs: List[str], m: int, n: int) -> int:\n \n dp = [[0 for i in range(m+1)] for i in range(n+1)]\n \n for s in strs:\n ones = s.count("1")\n zeros = s.count("0")\n \n for i in range(n,ones-1,-1):\n ...
6
You are given an array of binary strings `strs` and two integers `m` and `n`. Return _the size of the largest subset of `strs` such that there are **at most**_ `m` `0`_'s and_ `n` `1`_'s in the subset_. A set `x` is a **subset** of a set `y` if all elements of `x` are also elements of `y`. **Example 1:** **Input:**...
null
Binary Search Python Explained
heaters
0
1
# Intuition\nset the left and right pointer over heater arrays and for every house in house array find the nearest heater present near it.\nFor each house we are supposed to find the nearest array located to it.\nFrom that found locations return the maximum distance as the max radius required by any one of the heater t...
1
Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses. Every house can be warmed, as long as the house is within the heater's warm radius range. Given the positions of `houses` and `heaters` on a horizontal line, return _the minimum radius ...
null
Simple loop
heaters
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(Number of houses+ Number of heaters)\n- Space complexity:\n<!-- Add yo...
1
Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses. Every house can be warmed, as long as the house is within the heater's warm radius range. Given the positions of `houses` and `heaters` on a horizontal line, return _the minimum radius ...
null
Python Two Pointers and Binary Search Solution
heaters
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
Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses. Every house can be warmed, as long as the house is within the heater's warm radius range. Given the positions of `houses` and `heaters` on a horizontal line, return _the minimum radius ...
null
python 99.84% speed O(1) memory
heaters
0
1
# Intuition\nmax min problem\n\n# Approach\nSort all of the lists.\nChecking for every house closest heater and solving max min problem.\nFor example:\n-1 = heater\n1 = house\n\n1|1|1|1|-1|1|1|1|1|-1|1|1|1|1\nHere we should try for every house find closest heater. Compare it to max value, which we already have, save if...
3
Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses. Every house can be warmed, as long as the house is within the heater's warm radius range. Given the positions of `houses` and `heaters` on a horizontal line, return _the minimum radius ...
null
Python3, Binary search
heaters
0
1
# Intuition\n\nSince the heaters array cannot be empty, every house would have a heater that is the closest one to that house. The goal is to calculate the distance to the closest heater for every house and then return the maximum among them. By doing this we will fulfill the requirement of the problem to have every ho...
7
Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses. Every house can be warmed, as long as the house is within the heater's warm radius range. Given the positions of `houses` and `heaters` on a horizontal line, return _the minimum radius ...
null
[Python] - Greedy - O(nlogn) runtime and O(1) extra space
heaters
0
1
```\nclass Solution:\n def findRadius(self, houses: List[int], heaters: List[int]) -> int:\n houses.sort()\n heaters.sort()\n \n max_r = 0\n heater = 0\n \n for i,house in enumerate(houses):\n # Greedy: check if the next heater will shorter the radius compa...
1
Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses. Every house can be warmed, as long as the house is within the heater's warm radius range. Given the positions of `houses` and `heaters` on a horizontal line, return _the minimum radius ...
null
475: Solution with step by step explanation
heaters
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Sort the houses and heaters in ascending order.\n2. Initialize a variable result to 0.\n3. For each house, find the closest heater to the left and right using binary search (i.e. use bisect.bisect_right to find the first ...
4
Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses. Every house can be warmed, as long as the house is within the heater's warm radius range. Given the positions of `houses` and `heaters` on a horizontal line, return _the minimum radius ...
null
Beats Space complexity 99.8% SIMPLE PYTHON SOLUTION
heaters
0
1
\n# Code\n```\nclass Solution:\n def findRadius(self, houses: List[int], heaters: List[int]) -> int:\n c=0\n houses.sort()\n heaters.sort()\n dist=[]\n for i in houses:\n res=bisect_left(heaters,i)\n if(res==0):\n dist.append(abs(heaters[res]-i)...
1
Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses. Every house can be warmed, as long as the house is within the heater's warm radius range. Given the positions of `houses` and `heaters` on a horizontal line, return _the minimum radius ...
null
Easy python solution with 90% SC and 50% TC
heaters
0
1
```\ndef findRadius(self, houses: List[int], heaters: List[int]) -> int:\n\tdef isValid(rad):\n\t\th = 0\n\t\ti = 0\n\t\twhile(i < len(houses)):\n\t\t\tif(abs(houses[i] - heaters[h]) <= rad):\n\t\t\t\ti += 1\n\t\t\telse:\n\t\t\t\th += 1\n\t\t\tif(h == len(heaters)):\n\t\t\t\treturn 0\n\t\treturn 1\n\thouses.sort()\n\th...
1
Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses. Every house can be warmed, as long as the house is within the heater's warm radius range. Given the positions of `houses` and `heaters` on a horizontal line, return _the minimum radius ...
null
Binary Search - Python
heaters
0
1
\n```\nIn a anutshell, \n\tFor each house, we find the distance to the nearest heater.\nMax of the above distances, is the result.\n\nFor eg:\n\nhouses 1 2 3 4 5\nheaters h. h\n\nfor house 1,\n\tnearest heater is at distance 1, i.e at position 2\nfor house 2,\n\tnearest heater is at distance 0, i.e at...
2
Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses. Every house can be warmed, as long as the house is within the heater's warm radius range. Given the positions of `houses` and `heaters` on a horizontal line, return _the minimum radius ...
null
Python easy-understanding greedy solution.
heaters
0
1
```\nclass Solution:\n def findRadius(self, houses: List[int], heaters: List[int]) -> int:\n houses.sort()\n heaters.sort()\n res = 0\n heater = 0\n \n for h in houses:\n while heater + 1 < len(heaters) and heaters[heater + 1] == heaters[heater]: ...
3
Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses. Every house can be warmed, as long as the house is within the heater's warm radius range. Given the positions of `houses` and `heaters` on a horizontal line, return _the minimum radius ...
null
[Python3] greedy
heaters
0
1
\n```\nclass Solution:\n def findRadius(self, houses: List[int], heaters: List[int]) -> int:\n heaters.sort()\n ans = k = 0 \n for x in sorted(houses):\n while k < len(heaters) and heaters[k] < x: k += 1\n cand = inf \n if k < len(heaters): cand = min(cand, heate...
2
Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses. Every house can be warmed, as long as the house is within the heater's warm radius range. Given the positions of `houses` and `heaters` on a horizontal line, return _the minimum radius ...
null
Binary Search
heaters
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nBinary search using build-in method bisect_right in Python\n# Complexity\n- Time complexity: *MlogM + NlogN where (*MlogM depend on sorting of programing language\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!--...
0
Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses. Every house can be warmed, as long as the house is within the heater's warm radius range. Given the positions of `houses` and `heaters` on a horizontal line, return _the minimum radius ...
null
Python | Looping binary search
heaters
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
Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses. Every house can be warmed, as long as the house is within the heater's warm radius range. Given the positions of `houses` and `heaters` on a horizontal line, return _the minimum radius ...
null
Python3 Simple Binary Search
heaters
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIntial idea is to search through all of the heaters and find the closest heater to the a house. we do this for every house and the heater that is the furthest from any house becomes our minimum required radius so that all homes are heated...
0
Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses. Every house can be warmed, as long as the house is within the heater's warm radius range. Given the positions of `houses` and `heaters` on a horizontal line, return _the minimum radius ...
null
python3 code with O(n) time and space complexity
number-complement
0
1
# Intuition\nThe code first converts the given integer into binary using the built-in bin() function. Then, it iterates over each bit in the binary string and checks if it is 0 or 1. If it is 0, it appends 1 to a list, and if it is 1, it appends 0 to the list.\n\nAfter iterating over all bits in the binary string, the ...
1
The **complement** of an integer is the integer you get when you flip all the `0`'s to `1`'s and all the `1`'s to `0`'s in its binary representation. * For example, The integer `5` is `"101 "` in binary and its **complement** is `"010 "` which is the integer `2`. Given an integer `num`, return _its complement_. **...
null
[Python3] | Rumtime > 97%| Simple Solution
number-complement
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
The **complement** of an integer is the integer you get when you flip all the `0`'s to `1`'s and all the `1`'s to `0`'s in its binary representation. * For example, The integer `5` is `"101 "` in binary and its **complement** is `"010 "` which is the integer `2`. Given an integer `num`, return _its complement_. **...
null
476: Solution with step by step explanation
number-complement
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Convert the given integer \'num\' to its binary string representation using the built-in \'bin()\' function in Python.\n2. Flip all bits in the binary string obtained in step 1 to obtain the binary string representation o...
4
The **complement** of an integer is the integer you get when you flip all the `0`'s to `1`'s and all the `1`'s to `0`'s in its binary representation. * For example, The integer `5` is `"101 "` in binary and its **complement** is `"010 "` which is the integer `2`. Given an integer `num`, return _its complement_. **...
null
Solution
number-complement
1
1
```C++ []\nclass Solution {\npublic:\n int findComplement(int num) {\n int n = 0;\n int a = num;\n while(num > 0){\n num >>= 1;\n n ++;\n }\n cout << n;\n n = pow(2, n ) - 1;\n return n - a;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n ...
2
The **complement** of an integer is the integer you get when you flip all the `0`'s to `1`'s and all the `1`'s to `0`'s in its binary representation. * For example, The integer `5` is `"101 "` in binary and its **complement** is `"010 "` which is the integer `2`. Given an integer `num`, return _its complement_. **...
null
[Python3] Easy One line Code -with Explanation
number-complement
0
1
Here\'s the code:\n```python\nclass Solution:\n def findComplement(self, num: int) -> int:\n return num^(2**(len(bin(num)[2:]))-1)\n```\nWhat does it mean?\nThe complement of a number is computable by "flipping" all the bits in his binary form.\nIn other words, that\'s nothing more than a **bitwise XOR with a...
40
The **complement** of an integer is the integer you get when you flip all the `0`'s to `1`'s and all the `1`'s to `0`'s in its binary representation. * For example, The integer `5` is `"101 "` in binary and its **complement** is `"010 "` which is the integer `2`. Given an integer `num`, return _its complement_. **...
null
Python 3 one-line solution beats 42%
number-complement
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nConvert to binary and replace the 1\'s with 2 and 0 with 1 and 2 with 0 then convert back to an integer.\n\n# Code\n```\nclass Solution:\n def findComplement(self, num: int) -> int:\n return int(bin(num)[2:].replace(\'1\', \'2\'...
1
The **complement** of an integer is the integer you get when you flip all the `0`'s to `1`'s and all the `1`'s to `0`'s in its binary representation. * For example, The integer `5` is `"101 "` in binary and its **complement** is `"010 "` which is the integer `2`. Given an integer `num`, return _its complement_. **...
null
✔️ [Python3] BITWISE OPERATORS •͡˘㇁•͡˘, Explained
number-complement
0
1
The idea is to shift all bits of the given integer to the right in the loop until it turns into `0`. Every time we do a shift we use a mask to check what is in the right-most bit of the number. If bit is `0` we add `2**n` to the result where `n` is the current number of shifts. Example:\n```\nn=0, num=1010, bit=0 => re...
8
The **complement** of an integer is the integer you get when you flip all the `0`'s to `1`'s and all the `1`'s to `0`'s in its binary representation. * For example, The integer `5` is `"101 "` in binary and its **complement** is `"010 "` which is the integer `2`. Given an integer `num`, return _its complement_. **...
null
Python O( lg n ) sol. by XOR masking. 85%+ [ With explanation ]
number-complement
0
1
Python O( log n ) sol. based on XOR masking. \n\n---\n\nExample explanation\n\n---\nExample_#1\n\ninput: **5**\n\n5 = 0b **101**\n**bits length** of 5 = **3**\n**masking** = **2^3 -1** = 8 - 1 = **7** = 0b **111**\n\n5 = 0b **101**\n3 = 0b **111** ( **XOR** )\n\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\n**2...
19
The **complement** of an integer is the integer you get when you flip all the `0`'s to `1`'s and all the `1`'s to `0`'s in its binary representation. * For example, The integer `5` is `"101 "` in binary and its **complement** is `"010 "` which is the integer `2`. Given an integer `num`, return _its complement_. **...
null
Explained | Easy to understand | Faster than 99.58% | Simple | Bit manipulation | Python Solution
number-complement
0
1
##### Later I found that this solution correponds to the second approach mentioned in the solution\n\nHere, in this soution, we are just making another bit variable to be full of 1\'s upto the length of bits in num and then simply returning the XOR of two\nnum = 5 = 101\nbit ===== 111\nAns ==== 010 = 2\n\n```\ndef find...
17
The **complement** of an integer is the integer you get when you flip all the `0`'s to `1`'s and all the `1`'s to `0`'s in its binary representation. * For example, The integer `5` is `"101 "` in binary and its **complement** is `"010 "` which is the integer `2`. Given an integer `num`, return _its complement_. **...
null
Python3 | 1 liner | xor logic
number-complement
0
1
First solved it with the array/list approach to individually inverse the elements. Then, thought of how to implement a not gate using other bitwise operators and realised A xor 1 = not A.\n1*len(bin(num) is for creating the same length of 1\'s to xor each element with and [2:] slicing is to discard the \'0b\' represent...
3
The **complement** of an integer is the integer you get when you flip all the `0`'s to `1`'s and all the `1`'s to `0`'s in its binary representation. * For example, The integer `5` is `"101 "` in binary and its **complement** is `"010 "` which is the integer `2`. Given an integer `num`, return _its complement_. **...
null
99.20% faster python MUCH easy solution.
number-complement
0
1
```\nclass Solution:\n def findComplement(self, num: int) -> int:\n complement=""\n for i in bin(num)[2:]:\n if i is "0":\n complement+="1"\n else:\n complement+="0"\n \n return int(complement,2)\n```
7
The **complement** of an integer is the integer you get when you flip all the `0`'s to `1`'s and all the `1`'s to `0`'s in its binary representation. * For example, The integer `5` is `"101 "` in binary and its **complement** is `"010 "` which is the integer `2`. Given an integer `num`, return _its complement_. **...
null
Python 3 | Bit Manipulation O(N) | Explanations
total-hamming-distance
0
1
### Explanation\n- For each bit, count how many numbers have 0 or 1 on that bit; the total difference on that bit is `zero * one`\n\t- `zero`: the amount of numbers which have `0` on bit `i`\n\t- `one`: the amount of numbers which have `1` on bit `i`\n- Sum up each bit, then we got the answer\n- Time Complexity: `O(32*...
33
The [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance) between two integers is the number of positions at which the corresponding bits are different. Given an integer array `nums`, return _the sum of **Hamming distances** between all the pairs of the integers in_ `nums`. **Example 1:** **Input:** num...
null
One-line Python solution beats 98%
total-hamming-distance
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy first thought on how to solve this problem was to find the Hamming Distance between each pair of integers in the given list. The Hamming Distance between two integers is the number of positions at which the corresponding bits are diffe...
2
The [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance) between two integers is the number of positions at which the corresponding bits are different. Given an integer array `nums`, return _the sum of **Hamming distances** between all the pairs of the integers in_ `nums`. **Example 1:** **Input:** num...
null
Easy python solution
total-hamming-distance
0
1
# Code\n```\nclass Solution:\n def totalHammingDistance(self, nums: List[int]) -> int:\n ans=0\n for i in range(32):\n cnt=0\n for j in range(len(nums)):\n cnt+=(nums[j]>>i&1)\n ans+=(len(nums)-cnt)*cnt\n return ans\n```
4
The [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance) between two integers is the number of positions at which the corresponding bits are different. Given an integer array `nums`, return _the sum of **Hamming distances** between all the pairs of the integers in_ `nums`. **Example 1:** **Input:** num...
null
477: Solution with step by step explanation
total-hamming-distance
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Define a function named totalHammingDistance that takes a list of integers nums as input and returns an integer as output.\n2. Get the length of the nums list and store it in a variable n.\n3. Initialize a variable result...
3
The [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance) between two integers is the number of positions at which the corresponding bits are different. Given an integer array `nums`, return _the sum of **Hamming distances** between all the pairs of the integers in_ `nums`. **Example 1:** **Input:** num...
null
Easy and Clear Solution Python 3
total-hamming-distance
0
1
```\nclass Solution:\n def totalHammingDistance(self, nums: List[int]) -> int:\n res=0\n getbinary = lambda x, n: format(x, \'b\').zfill(n)\n bi=[]\n for i in range(len(nums)):\n a=getbinary(nums[i], 32)\n bi.append(a)\n for i in range (32):\n zero=...
1
The [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance) between two integers is the number of positions at which the corresponding bits are different. Given an integer array `nums`, return _the sum of **Hamming distances** between all the pairs of the integers in_ `nums`. **Example 1:** **Input:** num...
null
Python 3, TC: O(n)
total-hamming-distance
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(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $...
0
The [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance) between two integers is the number of positions at which the corresponding bits are different. Given an integer array `nums`, return _the sum of **Hamming distances** between all the pairs of the integers in_ `nums`. **Example 1:** **Input:** num...
null
easy solution || python3
total-hamming-distance
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
The [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance) between two integers is the number of positions at which the corresponding bits are different. Given an integer array `nums`, return _the sum of **Hamming distances** between all the pairs of the integers in_ `nums`. **Example 1:** **Input:** num...
null
Bit manuplation | Easy
total-hamming-distance
0
1
# Intuition\nThe "Total Hamming Distance" problem involves calculating the sum of Hamming distances between all pairs of integers in the given list `nums`. The Hamming distance between two integers is defined as the number of differing bits in their binary representations. Our initial thoughts are to find a way to effi...
0
The [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance) between two integers is the number of positions at which the corresponding bits are different. Given an integer array `nums`, return _the sum of **Hamming distances** between all the pairs of the integers in_ `nums`. **Example 1:** **Input:** num...
null
Simple and clear python3 solutions | Bit manipulation
total-hamming-distance
0
1
# Complexity\n- Time complexity: $$O(n \\cdot k) = O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(k) = O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\nwhere `n = nums.length` and `k = log2(max(nums)) = log2(10^9) ~ 30 = O(1)`\n# Code\n``` python3 []\nclass Sol...
0
The [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance) between two integers is the number of positions at which the corresponding bits are different. Given an integer array `nums`, return _the sum of **Hamming distances** between all the pairs of the integers in_ `nums`. **Example 1:** **Input:** num...
null
Better solution!
total-hamming-distance
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
The [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance) between two integers is the number of positions at which the corresponding bits are different. Given an integer array `nums`, return _the sum of **Hamming distances** between all the pairs of the integers in_ `nums`. **Example 1:** **Input:** num...
null
Simple step by step explanation , in Python
total-hamming-distance
0
1
# Code\n```\nclass Solution:\n def totalHammingDistance(self, nums: List[int]) -> int:\n # Can calculate ans ==> count of given integers whose ith it is set\n # if x of them has ith bit as set \n """\n ==> 1*(n-x) + 1*(n-x)+........x times.\n \n ==> x*(n-x)\n """\n\n ...
0
The [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance) between two integers is the number of positions at which the corresponding bits are different. Given an integer array `nums`, return _the sum of **Hamming distances** between all the pairs of the integers in_ `nums`. **Example 1:** **Input:** num...
null
Easy Python Solution
total-hamming-distance
0
1
\n# Code\n```\nclass Solution:\n def totalHammingDistance(self, nums: List[int]) -> int:\n arr=[]\n l=0\n if len(nums)<2:\n return 0\n for i in range(len(nums)):\n l=max(l, len(bin(nums[i])[2:]))\n arr.append(bin(nums[i])[2:])\n for i in range(len(a...
0
The [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance) between two integers is the number of positions at which the corresponding bits are different. Given an integer array `nums`, return _the sum of **Hamming distances** between all the pairs of the integers in_ `nums`. **Example 1:** **Input:** num...
null
Solution
generate-random-point-in-a-circle
1
1
```C++ []\nclass Solution {\nprivate:\n double r, x, y;\npublic:\n Solution(double radius, double x_center, double y_center) {\n r = radius;\n x = x_center;\n y = y_center;\n }\n double random(){\n return (double) rand() / RAND_MAX;\n }\n vector<double> randPoint() {\n ...
1
Given the radius and the position of the center of a circle, implement the function `randPoint` which generates a uniform random point inside the circle. Implement the `Solution` class: * `Solution(double radius, double x_center, double y_center)` initializes the object with the radius of the circle `radius` and th...
null
Solution
generate-random-point-in-a-circle
1
1
```C++ []\nclass Solution {\nprivate:\n double r, x, y;\npublic:\n Solution(double radius, double x_center, double y_center) {\n r = radius;\n x = x_center;\n y = y_center;\n }\n double random(){\n return (double) rand() / RAND_MAX;\n }\n vector<double> randPoint() {\n ...
1
Given an integer array `nums`, partition it into two (contiguous) subarrays `left` and `right` so that: * Every element in `left` is less than or equal to every element in `right`. * `left` and `right` are non-empty. * `left` has the smallest possible size. Return _the length of_ `left` _after such a partitioni...
null
Python3 Solution
generate-random-point-in-a-circle
0
1
\tclass Solution:\n\n\t\tdef __init__(self, radius: float, x_center: float, y_center: float):\n\t\t\tself.r = radius\n\t\t\tself.x, self.y = x_center, y_center\n \n\n\t\tdef randPoint(self) -> List[float]:\n\t\t\ttheta = uniform(0,2*pi)\n\t\t\tR = sqrt(uniform(0,self.r**2))\n\t\t\treturn [self.x+R*cos(theta), se...
3
Given the radius and the position of the center of a circle, implement the function `randPoint` which generates a uniform random point inside the circle. Implement the `Solution` class: * `Solution(double radius, double x_center, double y_center)` initializes the object with the radius of the circle `radius` and th...
null
Python3 Solution
generate-random-point-in-a-circle
0
1
\tclass Solution:\n\n\t\tdef __init__(self, radius: float, x_center: float, y_center: float):\n\t\t\tself.r = radius\n\t\t\tself.x, self.y = x_center, y_center\n \n\n\t\tdef randPoint(self) -> List[float]:\n\t\t\ttheta = uniform(0,2*pi)\n\t\t\tR = sqrt(uniform(0,self.r**2))\n\t\t\treturn [self.x+R*cos(theta), se...
3
Given an integer array `nums`, partition it into two (contiguous) subarrays `left` and `right` so that: * Every element in `left` is less than or equal to every element in `right`. * `left` and `right` are non-empty. * `left` has the smallest possible size. Return _the length of_ `left` _after such a partitioni...
null
478: Solution with step by step explanation
generate-random-point-in-a-circle
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Initialize the class with radius, x_center, and y_center as instance variables.\n2. When randPoint() is called, generate a random length between 0 and radius using random.uniform(0, self.radius**2).\n3. Generate a random ...
3
Given the radius and the position of the center of a circle, implement the function `randPoint` which generates a uniform random point inside the circle. Implement the `Solution` class: * `Solution(double radius, double x_center, double y_center)` initializes the object with the radius of the circle `radius` and th...
null
478: Solution with step by step explanation
generate-random-point-in-a-circle
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Initialize the class with radius, x_center, and y_center as instance variables.\n2. When randPoint() is called, generate a random length between 0 and radius using random.uniform(0, self.radius**2).\n3. Generate a random ...
3
Given an integer array `nums`, partition it into two (contiguous) subarrays `left` and `right` so that: * Every element in `left` is less than or equal to every element in `right`. * `left` and `right` are non-empty. * `left` has the smallest possible size. Return _the length of_ `left` _after such a partitioni...
null
Python easy - understanding solution with detailed explanation.
generate-random-point-in-a-circle
0
1
The idea is finding random angle and random radius, combining them together to get a random point on 2D circle.\nAt first, I really stuck for a long time with this code:\n```\nr = random.random() * self.r # Get wrong answer with test 7. Because it won\'t distribute evenly on circle.\n```\nAnd yeh, finally I found it ...
3
Given the radius and the position of the center of a circle, implement the function `randPoint` which generates a uniform random point inside the circle. Implement the `Solution` class: * `Solution(double radius, double x_center, double y_center)` initializes the object with the radius of the circle `radius` and th...
null
Python easy - understanding solution with detailed explanation.
generate-random-point-in-a-circle
0
1
The idea is finding random angle and random radius, combining them together to get a random point on 2D circle.\nAt first, I really stuck for a long time with this code:\n```\nr = random.random() * self.r # Get wrong answer with test 7. Because it won\'t distribute evenly on circle.\n```\nAnd yeh, finally I found it ...
3
Given an integer array `nums`, partition it into two (contiguous) subarrays `left` and `right` so that: * Every element in `left` is less than or equal to every element in `right`. * `left` and `right` are non-empty. * `left` has the smallest possible size. Return _the length of_ `left` _after such a partitioni...
null
Python, wrong test cases?
generate-random-point-in-a-circle
0
1
Quick answer: No, they are fine. Check out the answer by @mallikab. I\'ll let this post stand because of the discussion it has generated, but otherwise, both the solution presented below and the assumption of test cases being wrong is false.\n\n# UPD: Wrong claim, because 0.01 > 0.002:\nThe case below is wrong, the exp...
4
Given the radius and the position of the center of a circle, implement the function `randPoint` which generates a uniform random point inside the circle. Implement the `Solution` class: * `Solution(double radius, double x_center, double y_center)` initializes the object with the radius of the circle `radius` and th...
null
Python, wrong test cases?
generate-random-point-in-a-circle
0
1
Quick answer: No, they are fine. Check out the answer by @mallikab. I\'ll let this post stand because of the discussion it has generated, but otherwise, both the solution presented below and the assumption of test cases being wrong is false.\n\n# UPD: Wrong claim, because 0.01 > 0.002:\nThe case below is wrong, the exp...
4
Given an integer array `nums`, partition it into two (contiguous) subarrays `left` and `right` so that: * Every element in `left` is less than or equal to every element in `right`. * `left` and `right` are non-empty. * `left` has the smallest possible size. Return _the length of_ `left` _after such a partitioni...
null
Python Solution O(n)
generate-random-point-in-a-circle
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is to randomly generate points within a circle of radius radius and center point (x_center, y_center).\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach is to use the built-in random.uniform(a,...
2
Given the radius and the position of the center of a circle, implement the function `randPoint` which generates a uniform random point inside the circle. Implement the `Solution` class: * `Solution(double radius, double x_center, double y_center)` initializes the object with the radius of the circle `radius` and th...
null
Python Solution O(n)
generate-random-point-in-a-circle
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is to randomly generate points within a circle of radius radius and center point (x_center, y_center).\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach is to use the built-in random.uniform(a,...
2
Given an integer array `nums`, partition it into two (contiguous) subarrays `left` and `right` so that: * Every element in `left` is less than or equal to every element in `right`. * `left` and `right` are non-empty. * `left` has the smallest possible size. Return _the length of_ `left` _after such a partitioni...
null
✅✅ Beats 100% || RUBY || Easy to understand || 🔥🔥 ||
largest-palindrome-product
0
1
# Ruby\n```\n# @param {Integer} n\n# @return {Integer}\ndef largest_palindrome(n)\n return 9 if n == 1\n upper = (10.pow(n)) - 1 \n lower = 10.pow(n-1)\n i = upper\n (lower).times do\n i = i - 1\n s = i.to_s\n pal = (s + s.reverse).to_i\n lPal = ((pal.pow(0.5))-1).to_i\n ...
1
Given an integer n, return _the **largest palindromic integer** that can be represented as the product of two `n`\-digits integers_. Since the answer can be very large, return it **modulo** `1337`. **Example 1:** **Input:** n = 2 **Output:** 987 Explanation: 99 x 91 = 9009, 9009 % 1337 = 987 **Example 2:** **Input:...
null
Solution
largest-palindrome-product
1
1
```C++ []\nclass Solution {\npublic:\n int flip(int n){\n auto str = to_string(n);\n std::reverse(str.begin(), str.end());\n return atoi(str.c_str());\n }\n bool isInteger(double v){\n double tmp;\n return std::modf(v, &tmp) == 0.0;\n }\n int largestPalindrome(int n) {\...
2
Given an integer n, return _the **largest palindromic integer** that can be represented as the product of two `n`\-digits integers_. Since the answer can be very large, return it **modulo** `1337`. **Example 1:** **Input:** n = 2 **Output:** 987 Explanation: 99 x 91 = 9009, 9009 % 1337 = 987 **Example 2:** **Input:...
null
[Python3] Solution with explanation
largest-palindrome-product
0
1
```\nclass Solution:\n def largestPalindrome(self, n: int) -> int:\n # just to forget about 1-digit case\n if n == 1:\n return 9\n \n # min number with n digits (for ex. for n = 4, min_num = 1000)\n min_num = 10 ** (n - 1)\n \n # max number with n digits (f...
12
Given an integer n, return _the **largest palindromic integer** that can be represented as the product of two `n`\-digits integers_. Since the answer can be very large, return it **modulo** `1337`. **Example 1:** **Input:** n = 2 **Output:** 987 Explanation: 99 x 91 = 9009, 9009 % 1337 = 987 **Example 2:** **Input:...
null
479: Solution with step by step explanation
largest-palindrome-product
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. If n is 1, return 9.\n2. Set upper to the largest n-digit number (10^n - 1) and lower to the smallest n-digit number (10^(n-1)).\n3. Starting from upper, iterate through all possible n-digit numbers i in descending order....
3
Given an integer n, return _the **largest palindromic integer** that can be represented as the product of two `n`\-digits integers_. Since the answer can be very large, return it **modulo** `1337`. **Example 1:** **Input:** n = 2 **Output:** 987 Explanation: 99 x 91 = 9009, 9009 % 1337 = 987 **Example 2:** **Input:...
null
✅Python Fast. Swift 100% faster 100% less memory. No cheating.🔥
largest-palindrome-product
0
1
This is a very efficient solution for solving the problem; turns out to be a very straightforward way. Hint: it\'s about solving quadratic equations.\n```\nproduct = multiplicand * multiplier\nNow for an n-digit number, the maximum a multiplicand or a multiplier can be is (10\u207F - 1). So,\nproduct = \n = (...
6
Given an integer n, return _the **largest palindromic integer** that can be represented as the product of two `n`\-digits integers_. Since the answer can be very large, return it **modulo** `1337`. **Example 1:** **Input:** n = 2 **Output:** 987 Explanation: 99 x 91 = 9009, 9009 % 1337 = 987 **Example 2:** **Input:...
null
Short(est), Intuitive, Fast Solution (Python)
largest-palindrome-product
0
1
\n# Code\nSee explanation below!\n```py\nclass Solution:\n def largestPalindrome(self, n: int) -> int:\n if n == 1:\n return 9\n\n max_num = 10 ** n - 1\n min_num = 10 ** (n - 1)\n\n for num in range(int(max_num), int(min_num) - 1, -1):\n # Construct a palindrome by ...
0
Given an integer n, return _the **largest palindromic integer** that can be represented as the product of two `n`\-digits integers_. Since the answer can be very large, return it **modulo** `1337`. **Example 1:** **Input:** n = 2 **Output:** 987 Explanation: 99 x 91 = 9009, 9009 % 1337 = 987 **Example 2:** **Input:...
null
Meh
largest-palindrome-product
0
1
\n# Code\n```\nclass Solution:\n def largestPalindrome(self, n: int) -> int:\n if n == 1:\n return 9\n \n upper = 10 ** n - 1\n lower = 10 ** (n - 1)\n \n left_half = str(upper)[:n]\n \n while True:\n palindrome = int(left_half + left_half...
0
Given an integer n, return _the **largest palindromic integer** that can be represented as the product of two `n`\-digits integers_. Since the answer can be very large, return it **modulo** `1337`. **Example 1:** **Input:** n = 2 **Output:** 987 Explanation: 99 x 91 = 9009, 9009 % 1337 = 987 **Example 2:** **Input:...
null
PYTHON3. SIMPLE. WELL-COMMENTED.
largest-palindrome-product
0
1
# Intuition\nwell commented code, follow along. Comment any doubts! \n\n\n\n# Code\n```\nclass Solution:\n def largestPalindrome(self, n: int) -> int:\n if n== 1: # case if n = 1\n return 9\n upper = (10 ** n) -1 # for everything else. easy to cacluate upper and lower bound values.\n ...
0
Given an integer n, return _the **largest palindromic integer** that can be represented as the product of two `n`\-digits integers_. Since the answer can be very large, return it **modulo** `1337`. **Example 1:** **Input:** n = 2 **Output:** 987 Explanation: 99 x 91 = 9009, 9009 % 1337 = 987 **Example 2:** **Input:...
null
Commented and Explained, With Example 1 print log | Math Explained | Long Read
largest-palindrome-product
0
1
# Example One Print Log \ntotal boundary is 100\nCurrent upper boundary is 99\nCurrent lower boundary is 99\nResult of base squared minus 4 times lower boundary is -395\nCurrently not passing check one, as it has a value of -395\nRepeating with base value of 2\nCurrent upper boundary is 98\nCurrent lower boundary is 89...
0
Given an integer n, return _the **largest palindromic integer** that can be represented as the product of two `n`\-digits integers_. Since the answer can be very large, return it **modulo** `1337`. **Example 1:** **Input:** n = 2 **Output:** 987 Explanation: 99 x 91 = 9009, 9009 % 1337 = 987 **Example 2:** **Input:...
null
Python (Simple Maths)
largest-palindrome-product
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
Given an integer n, return _the **largest palindromic integer** that can be represented as the product of two `n`\-digits integers_. Since the answer can be very large, return it **modulo** `1337`. **Example 1:** **Input:** n = 2 **Output:** 987 Explanation: 99 x 91 = 9009, 9009 % 1337 = 987 **Example 2:** **Input:...
null
42ms (luck-based) solution Python
largest-palindrome-product
0
1
# Code\n```\nclass Solution:\n def largestPalindrome(self, n: int):\n if n == 1: return 9\n for i in range(1, 99999999):\n left = str(10**n - 2*i)\n right = left[::-1]\n if i**2 > int(right) \\\n and sqrt(i**2 - int(right)).is_integer():\n retu...
0
Given an integer n, return _the **largest palindromic integer** that can be represented as the product of two `n`\-digits integers_. Since the answer can be very large, return it **modulo** `1337`. **Example 1:** **Input:** n = 2 **Output:** 987 Explanation: 99 x 91 = 9009, 9009 % 1337 = 987 **Example 2:** **Input:...
null
Solution
sliding-window-median
1
1
```C++ []\nclass Solution {\npublic:\n vector<double> medianSlidingWindow(vector<int>& nums, int k) {\n vector<double> medians;\n unordered_map<int, int> hashTable;\n priority_queue<int> lo;\n priority_queue<int, vector<int>, greater<int>> hi;\n\n int i = 0;\n\n...
206
The **median** is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values. * For examples, if `arr = [2,3,4]`, the median is `3`. * For examples, if `arr = [1,2,3,4]`, the median is `(2 + 3) / 2 = 2.5`. You are give...
The simplest of solutions comes from the basic idea of finding the median given a set of numbers. We know that by definition, a median is the center element (or an average of the two center elements). Given an unsorted list of numbers, how do we find the median element? If you know the answer to this question, can we e...
Two Heaps, Lazy removals, Python3
sliding-window-median
0
1
# Intuition\nWant to use somehow changed version of MedianFinder from problem 295.\n\n# Approach\nThe class maintains a balance variable, which indicates the size difference between the two heaps. A negative balance\nindicates that the `small` heap has more elements, while a positive balance indicates that the `large` ...
8
The **median** is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values. * For examples, if `arr = [2,3,4]`, the median is `3`. * For examples, if `arr = [1,2,3,4]`, the median is `(2 + 3) / 2 = 2.5`. You are give...
The simplest of solutions comes from the basic idea of finding the median given a set of numbers. We know that by definition, a median is the center element (or an average of the two center elements). Given an unsorted list of numbers, how do we find the median element? If you know the answer to this question, can we e...
Treap solution O(nlogk) time O(k) space
sliding-window-median
0
1
\n\n```\nclass Solution:\n def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:\n tree = None\n ans = []\n for i, x in enumerate(nums):\n tree = insert(tree, x)\n if size(tree) > k:\n tree = remove(tree, nums[i - k])\n if size(tre...
1
The **median** is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values. * For examples, if `arr = [2,3,4]`, the median is `3`. * For examples, if `arr = [1,2,3,4]`, the median is `(2 + 3) / 2 = 2.5`. You are give...
The simplest of solutions comes from the basic idea of finding the median given a set of numbers. We know that by definition, a median is the center element (or an average of the two center elements). Given an unsorted list of numbers, how do we find the median element? If you know the answer to this question, can we e...
✅ Easiest Python O(n log k) Two Heaps (Lazy Removal), 96.23%
sliding-window-median
0
1
How to understand this solution:\n1) After we build our window, the length of window will ALWAYS be the same (now we will keep the length of valid elements in max_heap and min_heap the same too)\n2) Based on this, when we slide our window, the balance variable can be equal to 0, 2 or -2. It will NEVER be -1 or 1.\nExam...
31
The **median** is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values. * For examples, if `arr = [2,3,4]`, the median is `3`. * For examples, if `arr = [1,2,3,4]`, the median is `(2 + 3) / 2 = 2.5`. You are give...
The simplest of solutions comes from the basic idea of finding the median given a set of numbers. We know that by definition, a median is the center element (or an average of the two center elements). Given an unsorted list of numbers, how do we find the median element? If you know the answer to this question, can we e...
Python real O(nlogk) solution - easy to understand
sliding-window-median
0
1
**Solution 1: `O(nk)`**\nMaitain a sorted window. We can use binary search for remove and insert. \nBecause insert takes `O(k)`, the overall time complexity is `O(nk)`.\n\n**Solution 2: `O(nk)`**\nSimilar with LC 295, we need to maintain two heaps in the window, leftHq and rightHq. \nTo slide one step is actually to d...
51
The **median** is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values. * For examples, if `arr = [2,3,4]`, the median is `3`. * For examples, if `arr = [1,2,3,4]`, the median is `(2 + 3) / 2 = 2.5`. You are give...
The simplest of solutions comes from the basic idea of finding the median given a set of numbers. We know that by definition, a median is the center element (or an average of the two center elements). Given an unsorted list of numbers, how do we find the median element? If you know the answer to this question, can we e...
python solution using sliding window+bisect
sliding-window-median
0
1
Beats 98,2% Runtime and 56,77% Memory\n\n# Code\n```\nimport bisect\n\ndef medianaordenada(arr):\n d = len(arr)\n pos0 = (d - 1) // 2\n if d%2 == 0:\n return (arr[pos0]+arr[pos0+1])/2\n else:\n return arr[pos0]\n\nclass Solution:\n def medianSlidingWindow(self, nums: List[int], k: int) -> L...
1
The **median** is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values. * For examples, if `arr = [2,3,4]`, the median is `3`. * For examples, if `arr = [1,2,3,4]`, the median is `(2 + 3) / 2 = 2.5`. You are give...
The simplest of solutions comes from the basic idea of finding the median given a set of numbers. We know that by definition, a median is the center element (or an average of the two center elements). Given an unsorted list of numbers, how do we find the median element? If you know the answer to this question, can we e...
480: Solution with step by step explanation
sliding-window-median
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Check if the list is empty or the window size is greater than the list length. If either of these conditions is true, return an empty list.\n\n2. Create a helper function to calculate the median of a given subarray. If th...
3
The **median** is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values. * For examples, if `arr = [2,3,4]`, the median is `3`. * For examples, if `arr = [1,2,3,4]`, the median is `(2 + 3) / 2 = 2.5`. You are give...
The simplest of solutions comes from the basic idea of finding the median given a set of numbers. We know that by definition, a median is the center element (or an average of the two center elements). Given an unsorted list of numbers, how do we find the median element? If you know the answer to this question, can we e...
Python - Easy to understand using 2 heap
sliding-window-median
0
1
```\nimport heapq\n\nclass Solution:\n def getMedian(self, maxHeap: List[int], minHeap: List[int]) -> float:\n # minHeap stores larger half and maxHeap stores small half elements\n # So data is like -> [maxHeap] + [minHeap]\n # if total no of element is odd, then maxHeap contains more elements t...
3
The **median** is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values. * For examples, if `arr = [2,3,4]`, the median is `3`. * For examples, if `arr = [1,2,3,4]`, the median is `(2 + 3) / 2 = 2.5`. You are give...
The simplest of solutions comes from the basic idea of finding the median given a set of numbers. We know that by definition, a median is the center element (or an average of the two center elements). Given an unsorted list of numbers, how do we find the median element? If you know the answer to this question, can we e...
Python3 O(nlogk) heap with intuitive lazy deletion - Sliding Window Median
sliding-window-median
0
1
```\nimport heapq\n\nclass Heap:\n def __init__(self, indices: List[int], nums: List[int], max=False) -> None:\n self.max = max\n self.heap = [[-nums[i], i] if self.max else [nums[i],i] for i in indices]\n self.indices = set(indices)\n heapq.heapify(self.heap)\n \n def __len__(s...
15
The **median** is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values. * For examples, if `arr = [2,3,4]`, the median is `3`. * For examples, if `arr = [1,2,3,4]`, the median is `(2 + 3) / 2 = 2.5`. You are give...
The simplest of solutions comes from the basic idea of finding the median given a set of numbers. We know that by definition, a median is the center element (or an average of the two center elements). Given an unsorted list of numbers, how do we find the median element? If you know the answer to this question, can we e...
481. Magical String
magical-string
0
1
```\nclass Solution:\n def magicalString(self, n: int) -> int:\n arr, i = [1,2,2], 2\n \n while len(arr) < n:\n arr.extend([arr[-1]^3]*arr[i])\n i += 1\n \n return arr[:n].count(1)
3
A magical string `s` consists of only `'1'` and `'2'` and obeys the following rules: * The string s is magical because concatenating the number of contiguous occurrences of characters `'1'` and `'2'` generates the string `s` itself. The first few elements of `s` is `s = "1221121221221121122...... "`. If we group th...
null
Easy python solution with explanation
magical-string
0
1
1. We have to create the magic string upto length n.\n2. We will do that by using the string itself.\n3. So, one pointer will be telling us the count of the latest adding to the string.\n4. I hope that\'s well clear to you. If not then once again. If it is 2, then it\'s telling that something is in the count of 2, it c...
3
A magical string `s` consists of only `'1'` and `'2'` and obeys the following rules: * The string s is magical because concatenating the number of contiguous occurrences of characters `'1'` and `'2'` generates the string `s` itself. The first few elements of `s` is `s = "1221121221221121122...... "`. If we group th...
null
481: Solution with step by step explanation
magical-string
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Check if input n is 0, if so, return 0 as the output.\n\n2. Initialize the magical string s with the first three elements, which are 1, 2, 2.\n\n3. Initialize a variable i to 2, which will be used to keep track of the ind...
3
A magical string `s` consists of only `'1'` and `'2'` and obeys the following rules: * The string s is magical because concatenating the number of contiguous occurrences of characters `'1'` and `'2'` generates the string `s` itself. The first few elements of `s` is `s = "1221121221221121122...... "`. If we group th...
null
Two Pointer | One pass
magical-string
0
1
```\nclass Solution:\n def magicalString(self, n: int) -> int:\n if n in [1,2,3]:\n return 1\n s, p1, p2, curr, count = \'122\', 2, 3, \'1\', 1\n while p2 < n:\n s += curr * int(s[p1])\n p2 += int(s[p1])\n if curr == \'1\':\n if p2 > n:\...
1
A magical string `s` consists of only `'1'` and `'2'` and obeys the following rules: * The string s is magical because concatenating the number of contiguous occurrences of characters `'1'` and `'2'` generates the string `s` itself. The first few elements of `s` is `s = "1221121221221121122...... "`. If we group th...
null
Magical String
magical-string
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
A magical string `s` consists of only `'1'` and `'2'` and obeys the following rules: * The string s is magical because concatenating the number of contiguous occurrences of characters `'1'` and `'2'` generates the string `s` itself. The first few elements of `s` is `s = "1221121221221121122...... "`. If we group th...
null
Python 3 Solution
magical-string
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n 1. The idea is to construct the string first upto the constraint\n 2. Return the count of 1 in string upto n\n\n# Code\n```\n# Below is the construction of stri...
0
A magical string `s` consists of only `'1'` and `'2'` and obeys the following rules: * The string s is magical because concatenating the number of contiguous occurrences of characters `'1'` and `'2'` generates the string `s` itself. The first few elements of `s` is `s = "1221121221221121122...... "`. If we group th...
null
Faster than 100% of the Submissions (python, 77ms)
magical-string
0
1
# Intuition\nThere are about the same amount of 1\'s and 2\'s in the string (at least for long strings). This means the number of Packs $$p$$ is approximately $$p=\\frac{2}{1+2}\\cdot n\\approx0.667 \\cdot n$$ in a string of the length $$n$$.\n\n# Approach\nKnowing the relation of Packs $$p$$ to Digits $$n$$ allows us ...
0
A magical string `s` consists of only `'1'` and `'2'` and obeys the following rules: * The string s is magical because concatenating the number of contiguous occurrences of characters `'1'` and `'2'` generates the string `s` itself. The first few elements of `s` is `s = "1221121221221121122...... "`. If we group th...
null
Reverse traversing || Simple logic
license-key-formatting
0
1
\n\n# Code\n```\nclass Solution:\n def licenseKeyFormatting(self, s: str, k: int) -> str:\n s = s.replace(\'-\', \'\').upper()\n new_key , dup = \'\' , k\n\n for i in range(len(s)-1,-1,-1):\n if k!=0:\n new_key = s[i] + new_key\n k -= 1\n\n if ...
2
You are given a license key represented as a string `s` that consists of only alphanumeric characters and dashes. The string is separated into `n + 1` groups by `n` dashes. You are also given an integer `k`. We want to reformat the string `s` such that each group contains exactly `k` characters, except for the first g...
null
Python3 Solution using replace
license-key-formatting
0
1
# Intuition\n##### To solve this problem, we need to format the **license key** by grouping the characters into groups of \'k\' separated by hyphens and converting all characters to upper case. The approach can be to first remove all hyphens from the input string, convert it to upper case, and then iterate over the cha...
2
You are given a license key represented as a string `s` that consists of only alphanumeric characters and dashes. The string is separated into `n + 1` groups by `n` dashes. You are also given an integer `k`. We want to reformat the string `s` such that each group contains exactly `k` characters, except for the first g...
null
Python/JS/C++ O(n) by string operation. [w/ Explanation]
license-key-formatting
0
1
O(n) by string operation.\n\n---\n\n**Explanation**:\n\nFirst, eliminate all dashes.\n\nSecond, start **grouping with size = K**,\nRemember to make a special handle for first group in case that len(S) is not divisible by K.\n\nThird, link each group togetger, separated by dash, \'-\', at the junction point.\n\nFinally,...
45
You are given a license key represented as a string `s` that consists of only alphanumeric characters and dashes. The string is separated into `n + 1` groups by `n` dashes. You are also given an integer `k`. We want to reformat the string `s` such that each group contains exactly `k` characters, except for the first g...
null