kamyu104 / leetcode-solutions Goto Github PK
View Code? Open in Web Editor NEW๐๏ธ Python / Modern C++ Solutions of All 3141 LeetCode Problems (Weekly Update)
License: MIT License
๐๏ธ Python / Modern C++ Solutions of All 3141 LeetCode Problems (Weekly Update)
License: MIT License
While looping through the for loop xrange is used for finding out the range from where to loop in case of range
I was going through your code for 1358 no of substrings containing all 3 characters.
I am assuming that the purpose of the left variable is to keep track of where a,b,c occur in the string.
We then choose the min of those indices,and add min_index+1 to the count.
We do this for all chars in string and then return the final count.
Is that correct?
Detailed explanation is here
https://leetcode.com/problems/number-of-substrings-containing-all-three-characters/discuss/516955/Java-ELEGANT-No-Sliding-Window-EXPLAINED-(No-of-Sub-Strings-Ending-at-Curr-Index)
Also,if possible can you please add some explanation /reasoning for the codes.I know it will be difficult,but it helps us to understand how you came at the solution.
the [0] case not passed, resolve this problem below:
class Solution:
def minOperations(self, nums: List[int]) -> int:
def popcount(num):
result = 0
while num:
num &= num - 1
result += 1
return result
result, max_len = 0, 0
if len(nums) == 1 and nums[0] == 0:
return 0
else:
for num in nums:
result += popcount(num)
max_len = max(max_len, num.bit_length())
return result + max_len -1
Thk you kamyu very much! Your work is incredible. I learned a lot.
below is my approach for intersection-of-two-arrays-ii.cpp
#define be(x) begin(x), end(x)
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
vector<int> res;
sort(be(nums1)); sort(be(nums2));
set_intersection(be(nums1), be(nums2), back_inserter(res));
return res;
}
};
I am relatively new to python so kindly pardon me if my understanding is off. With that said, I wanted to confirm if the space complexity of your solution would still be O(1).
It seems to me that you are using the count variable (an object of the Counter class) to essentially keep a track of character frequency. Wouldn't that make the space complexity O(n)?
My bad, did not realize that n being 26, it is effectively O(n) = O(26)=> O(1)
Getting TLE exceeded for the following input
https://leetcode.com/submissions/detail/706759598/testcase/
guess-number-higher-or-lower-ii get error while running in leetcode enviroment
Line 1034: Char 34: runtime error: addition of unsigned offset to 0x6040000000d0 overflowed to 0x6040000000cc (stl_vector.h)
class Solution {
public:
int getMoneyAmount(int n) {
vector<vector<int>> pay(n + 1, vector<int>(n));
for (int i = n - 1; i >= 0; --i) {
for (int j = i + 1; j < n; ++j) {
pay[i][j] = numeric_limits<int>::max();
for (int k = i; k <= j; ++k) {
pay[i][j] = min(pay[i][j], k + 1 + max(pay[i][k - 1], pay[k + 1][j]));
}
}
}
return pay[0][n - 1];
}
};
Your code work fine in my local machie but can't pass in Leetcode envrioment.
Do you have any idea how to solve this?
Hi,I tried running your code on different test cases
[2,4,1,6,9,5,7] the expected output is 3 but the solution returns 0
Similarly for [2,1,6,4,3,7] the expected output should be 3 but actual output is 0.
I found these test cases here.
https://leetcode.com/discuss/interview-question/524146/
I think question is similar to 769
Hi, kamyu,
Thanks a lot for providing these awesome solutions, this is actually a question instead of an issue, and I am sorry I put it here since I didn't find any other way to leave a message to you. If you want me to move this somewhere else, I am totally glad to do.
I am wondering why "result.append(intermediate)" in the code doesn't give the right result. I printed out intermediate every time before appending to result and confirmed that it's a list. But inserting it without the list() function gives the wrong result.
class Solution(object):
def combinationSum(self, candidates, target):
result = []
self.combinationSumRecu(sorted(candidates), result, 0, [], target)
return result
def combinationSumRecu(self, candidates, result, start, intermediate, target):
if target == 0:
result.append(list(intermediate))
#why result.append(intermediate) doesn't give the right result?
while start < len(candidates) and candidates[start] <= target:
intermediate.append(candidates[start])
self.combinationSumRecu(candidates, result, start, intermediate, target - candidates[start])
intermediate.pop()
start += 1
Thanks a lot for your help.
Best,
Cindy
Is this equivalent to two separate lines like :
How to explain totalCount
, validCountInLessLength
, validCountInFullLength
in confusing-number-ii.py
?
"220. Contains Duplicate III" is causing runtime error on input:
Nums = [2147483647,-2147483647]
k = 1
t = 2147483647
Hello,
Sorry for opening an issue here, but I didn't know how else I could ask you this question.
I recently found out about leetcode and I challenged myself to solve at least one problem each day (from the free version for now). I also decided to store my work on github along with a readme in which I put both the text of the problem and how I went about solving it (mostly for my future reference). I was sure I was not the first one to come up with the idea of having the solutions on github and I wanted to see how other people structured their repository and that's how I found yours.
I noticed that in your README you you said "R.I.P. to my old Leetcode repository, where there were 5.7k+ stars and 2.2k+ forks (ever the top 3 in the field). Since free questions may be even mistakenly taken down by some companies, only solutions will be post on now." My aim is not to get stars or forks, but I did want to save the text of the problems that I solved next to my thoughts in order to have everything in one place so I wanted to ask:
Was your previous repo taken down solely because of the text of a problem (which is also publicly available for free on Leetcode as well) or were there other things that lead to the termination of that repo? Also, what would you recommend, should I stop saving the text of the problems ?
For video stiching the current code is giving the wrong answer for the below mentioned test case,leading to failure of submission
I/p: [[2,4]] 0
Current O/P -1
Expected O/P 0
While executing the code a run time error is generated
Hey Hii,
Do you have leetcode Premium subscription?
I just wanted the List of top Amazon questions in that in
Explore -> Top Amazon Questions Card
Can you Please Help me, I have Amazon Interview next week.
It would be very helpful if you could add a section for that.
Thanks in advance
Hi,
I found that some solutions are not listed on README.md. Can I add them or could you do that for me?
For example,
the-maze.py
In the problem it is mentioned that the subarray doesn't have to be distinct.I recieved a problem in my coding interview shown below
https://leetcode.com/discuss/interview-question/278341/Uber-phone-interview-Number-of-distinct-subarrays-with-at-most-k-odd-elements/265140
After reading the problem description and the subarray with k different integers,can we extend it to take into consideration odd elements.I tried doing that but I am getting 0 as my answer.Any suggestions will be welcome
Hello,can you explain why the compexity is O(N^2) and not O(N)
New version of leetcode 232 returns int instead of void in pop function
code fails to pass test case ["aaa,"acb"] heap overflow
https://github.com/kamyu104/LeetCode-Solutions/blob/master/Python/cheapest-flights-within-k-stops.py
The time analysis indicates O((|E| + |V|) * log|V|)
.
The typical Dijkstra's analysis involves the following:
This leaves us with (E + V)log(V) for a normal dijkstra's.
In your solution, your best cache is on both vertex and k. Which means you can visit each vertex up to K times.
So the analysis should be O(K(E + V)log(KV)) which should be ~ O(KE*LOG(V))
new test case causes program to fail
error is as follows
runtime error: signed integer overflow: 243 * 9586565 cannot be represented in type 'int' (solution.cpp)
Have you updated the solutions for last week's contests?couldn't find them or for the contest on 11th december?
Tried running the below code in python3 (changed xrange
to range
):
class Solution(object):
def minSwapsCouples(self, row):
"""
:type row: List[int]
:rtype: int
"""
N = len(row)//2
couples = [[] for _ in range(N)]
for seat, num in enumerate(row):
couples[num//2].append(seat//2)
adj = [[] for _ in range(N)]
for couch1, couch2 in couples:
adj[couch1].append(couch2)
adj[couch2].append(couch1)
result = 0
for couch in range(N):
if not adj[couch]: continue
couch1, couch2 = couch, adj[couch].pop()
while couch2 != couch:
result += 1
adj[couch2].remove(couch1)
couch1, couch2 = couch2, adj[couch2].pop()
return result # also equals to N - (# of cycles)
def main():
soln = Solution()
arr = [1, 3, 5, 2, 4, 6, 7]
min_swaps = soln.minSwapsCouples(arr)
print(min_swaps)
if __name__ == '__main__':
main()
With the below error:
Traceback (most recent call last):
File "min_swap_couples.py", line 33, in <module>
main()
File "min_swap_couples.py", line 29, in main
min_swaps = soln.minSwapsCouples(arr)
File "min_swap_couples.py", line 10, in minSwapsCouples
couples[num//2].append(seat//2)
IndexError: list index out of range
When I surfing the discussion about 488. Zuma Game, I notice that someone point out the corner case.
This special case is like following :
board : "WWRRWWBBWW"
hand : "RB"
If you list all possible case, it should retrun "2".
Solution as following:
board : "WWRRWWBBWW"
hand : "RB"
->
board : "WWRRWWBBWRW"
hand : "B"
->
board : "WWRRWWBBBWRW"->"WWRRWWWRW"->"WWRRRW"->"WWW"->""
hand : ""
However, the official solution can not pass this case neither.
The key point is that most of algorithm (including the c++ & python solution in this repo) will insert the balls with the same color. But the corner case show that it is not perfect algorithm for reducing the complexity.
Hi,
Would you be uploading the solutions to the recent contest 203 and bi weekly contest
Hi,
I have a question for a solution at the following link:
Line 31 has board[x][y] = 'V'
even we mardked board[i][j] = 'V' at line 27. Either way is fine for OJ but could you tell me why we need line 31?
Hi,I was running your solution for the above mentioned problem.It seems that if we create a vector of integers to represent then we get the following error:
"Runtime error signed integer overflow <large number addition cannot be represented by int?
The error goes away if we use unsigned integer representation.
Also can you please explain the logic behind the solution
How do you make sure that if the reversed integer overflows, the result must not equal the input. I mean,
maybe 12345999999 --reverse--> 99999954321 ---overflow---> 12345999999, and this is just an example.
My question is how do you know this kind of numbers do not exist.
In heightchecker.py for python3 instead of itertools.izip use zip.Of course if you're running on below python 3 then its fine.
This solution is not right anymore, you also need check connected components after OJ test cases updated.
Recieving runtime error signed integer overflow for single number iii
Python3 error:
Change xrange
to range
.
If not lost, subdivide it into folders so that it is visible on the repo.
Hi,
It seems that the Python solution of 685 Redundant Connection II might need to be improved because it doesn't work.
I wanted to contribute to the solution but I am still trying to solve the problem. :0
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.