Giter VIP home page Giter VIP logo

kamyu104 / leetcode-solutions Goto Github PK

View Code? Open in Web Editor NEW
4.5K 167.0 1.5K 23.99 MB

๐Ÿ‹๏ธ Python / Modern C++ Solutions of All 3123 LeetCode Problems (Weekly Update)

License: MIT License

C++ 53.99% Go 0.04% Java 0.13% Python 45.29% Shell 0.01% TypeScript 0.51% Ruby 0.01% PHP 0.01% C# 0.01% Swift 0.01% Rust 0.01% Kotlin 0.01%
leetcode python cpp algorithm data-structure cpp11 leetcode-solutions interview-questions interview-preparation interview-practice

leetcode-solutions's People

Contributors

0xkookoo avatar april12925 avatar arthur-github-user avatar b1z0n avatar bhainesva avatar chenkkkabc avatar chihyaoma avatar cmwenliu avatar donaldcao avatar harvey1993 avatar jinkecao avatar jxie0755 avatar kamyu104 avatar ken-yang avatar manoshape avatar megazone87 avatar needforspeed avatar nth-attempt avatar nycgithub avatar poweihuang17 avatar rancejen avatar sangheestyle avatar spy19930412 avatar theodoreguo avatar wenting-zhao avatar wilbeibi avatar xfbao1986 avatar xiaopeng163 avatar ycsheu avatar zhilianggong avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

leetcode-solutions's Issues

1558 the [0] case could not passed

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

The corner case in 488. Zuma Game

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.
image
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.

Heightchecker

In heightchecker.py for python3 instead of itertools.izip use zip.Of course if you're running on below python 3 then its fine.

Leetcode #765 Python Error: list index out of range

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

Leetcode 992 Subarray with k different integers

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

Amazon Interview Questions

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

Explanation for 1358 number of substrings containing all characters

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.

[Question] 0424 Longest repeating character replacement: Space complexity

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)

guess-number-higher-or-lower-ii runtime error

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?

for statistics from large sample

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)

Another approach for intersection-of-two-arrays-ii.cpp

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;
    }
};

What happened to your old Leetcode repository

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 ?

overflow issue

return reversed == x;

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.

A question regarding combination-sum.py

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

Wrong answer for Integer to Roman in Python

I ran the test cases using the code given on the repo and the answers are incorrect for multiple test cases. I am attaching a screenshot below.

image

Creating a pull request to replace the incorrect output with my solution which works on all test cases.

Leetcode 377 combination sum iv

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

A question about Dijkstra's cheapest flights analysis

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:

  1. You visit each vertex once. Therefore, the priority queue is up to V. So each heap operation is O(log(V))
  2. You visit all the edge once and each time involves an heap operation. So E log(V)
  3. Eventually, you remove all V from the heap. And so V log (V)

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))

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.