# Tag Info

7

Nice implementation, it's already very efficient. Few suggestions: Expand the variables in the for-loop from for q in queries to for a, b, k in queries. Given the problem description it's easier to read. A better name for the variable current can be running_sum. Avoid calling a variable max, since it's a built-in function in Python. An alternative name can ...

7

First of all, props for the copious comments, particularly how you included a representation in C. The C representation itself has a signed vs unsigned comparison, which can cause weird bugs when and where you don't expect them, but I'm going to stick to the assembly code itself in this review. I would just recommend declaring the loop counter i as size_t, ...

6

Your code is quite nice. Your use of functions seem quite reasonable. And your style is nice too. Good job! Calling print is expensive. To improve performance we can build the strings without using the for loop. For example to build $n-(i + 1)$ spaces we can use: >>> n = 12; i = 1 >>> " " * (n - (i + 1)) ' ' To build ...

5

Welcome to Code Review! PEP-8 In python, it is common (and recommended) to follow the PEP-8 style guide for writing clean, maintainable and consistent code. Functions and variables should be named in a lower_snake_case, classes as UpperCamelCase, and constants as UPPER_SNAKE_CASE. f-strings Newly introduced in python 3 is the f-string; so instead of having ...

5

Using the same type for the deque contents and the sizes/indices (k, count, head, tail) feels wrong. At least, k and count should be std::vector::size_type. Since you are backing up the deque with std::vector, making head and tail the std::vector::iterator looks more idiomatic. k is not the most descriptive name. Consider capacity. I am not sure that std::...

5

Your solution isn't $O(n)$ but $O(2^n)$. Your assumption that the tree is complete and thus your analysis is incorrect. Already LeetCode's second example tree isn't complete. And consider this tree: That tree only has 25 nodes, but your solution creates thousands of Nones for subtrees that aren't there. (That is, your actual code presumably does that, ...

4

Time & Memory Complexity Your code uses a lot of time and memory. With an $d$ digit number, you will get roughly $d!$ different permutations of digits. list(permutations(str(n))) will cause all of these permutations to be realized in a list $d!$ elements long. You take this list, and then repeatedly take one permutation from it, convert it into a ...

4

About __optimize__ Identifiers starting with double underscores are reserved. Also, why is this written as a lambda instead of as a regular function? You're also not reading and writing to standard I/O, so this function wouldn't have any effect anyway. Avoid creating type aliases outside of a class or namespace Don't declare using ValueType = int in the ...

4

You can call stream.reserve(k) in the constructor to improve the efficiency of the vector because you know that you will only have k elements, so .reserve() will pre-allocate the memory. Prefer using std::size_t over int int k would be std::size_t k You haven't declared a copy constructor nor a copy assignment operator. This can cause issues if you wanted to ...

4

You use three different names for the same thing. You ask for Height, then call it num, then call it n. I'd just call the variables height, both to be consistent and to be meaningful. At least in main and print_pyramid, as there it really means height. In print_spaces it's perhaps better to keep calling the parameter n, as that function doesn't need to know ...

4

Performance The main optimization that can be made here is to, while iterating over the sorted houses, to inch along the heaters one-by-one while testing their distance. Increment a heater index only if the difference between the house and the next heater is less than the difference between the house and the current heater. This way, whenever a heater is ...

4

You are doing the lookup twice. if (!encoded_url.count(long_url)) { .. stuff } else { tiny_encoded = encoded_url[long_url]; } I know that it is O(1) for the lookup. But there is a real constant inside that. Avoid it if you can. Use find(). Then if it is there you can simply use it. ...

4

There's a lot in your code that can be refactored but let's start from the beginning with some Python styleguides (also called PEP8) Imports It's recommended to write all the imports at the top of your file. Naming In Python, the name of functions and variables should be snake_cased. That is, instead of def Roll() you should have def roll(), instead of ...

3

You could use itertools.accumulate to shorten your second part a lot and make it faster: def arrayManipulation(n, queries): nums = [0] * (n + 1) for a, b, k in queries: nums[a - 1] += k nums[b] -= k return max(accumulate(nums)) Can be used on Marc's version as well. Benchmarks with various solutions on three worst case inputs: ...

3

I don't know of any way to optimize this; I suspect you've cracked the way it was intended to be implemented. The following are just general recommendations. Using black to format the code will make it closer to idiomatic style, with no manual work. After formatting I would recommend running flake8 to find remaining non-idiomatic code. For example, function ...

3

Others have made good points, but I'll add in a stylistic quibble. return std::size(short_url) != kDomainTinySize || !decoded_url.count(short_url.substr(kDomainSize, kTinySize)) ? "" : decoded_url[short_url.substr(kDomainSize, kTinySize)]; is a heck of a one-liner. The ternary operator is fun but speaking as someone who has ...

3

I agree with everything in Martin York's answer. Just one thing: you can avoid having two unordered_maps if you don't create a purely random URL, but instead create one by hashing the original URL. This way, you will always create the same tiny URL for the same long URL, so you don't need encoded_url anymore. Of course, you would still need to handle ...

3

Some minor stuff: This if: if simulated[i] == q[i]: continue is redundant and can be removed, due to the predicate on your while. The while would execute zero times and have the same effect as if you continued. The while itself: while(simulated[i] != q[i]): should drop the outer parens. The range here: for i in range(0, len(simulated)): ...

3

Unnecessary classes The snake, ladder and dice classes are not at all useful. They can simply be replaced with a namedtuple or a dataclass. Similarly, player and playerposition should both be a single class element. A player object should be responsible for keeping track of their position. Verbosity s1, s2, ... s8 and similary l1, l2, ... l8 are not really ...

3

I think this is a theme for your code: const, where you've put it, has no benefit; and it's missing from other places that it should be there. Every single function in MyCircularDeque should drop the const out front, because those return values are scalar so marking them const has literally no effect. insertLast(const int value) has slightly more effect but ...

3

Nice implementation, it's easy to understand and well structured. Few suggestions: Seat class class Seat: def __init__(self): pass class FirstClass(Seat): def __init__(self): super().__init__() self.tier = 'First Class' self.price = 500 class Coach(Seat): def __init__(self): super().__init__() ...

3

So from a small glance this looks good I would have gone with a union-find structure but I think it is a neat idea to store in the map. There are some things I would like to improve: You are missing [[nodiscard]] throughout, which I believe should be used nowadays. Formatting is a bit off for me. A few newlines here and there could help a lot with ...

3

It would also be easier if we follow TDD - Test Driven Development. We build the boiler plate that LeetCode is building for you. from __future__ import annotations import dataclasses from typing import Any, Optional @dataclasses.dataclass class Node: val: Any left: Optional[Node] = None right: Optional[Node] = None We get a tree with only one ...

3

O(1) space, O(n) time As kinda pointed out already, your lists of nodes/values of the current level are up to $O(2^n)$ large. So your large memory usage of 150 MB is no wonder. It could easily be much more. LeetCode must have only very shallow trees (Yeah just checked, max height is only 22. Sigh). Here's somewhat the other extreme, taking only O(1) extra ...

3

Here's a suggested implementation that changes basically nothing about your algorithm, but has proper indentation uses a little bit of type hinting uses set literals and generators uses _ for "unused" variables adds a parse_clause() because the clause code is repeated uses a StringIO, for these purposes, to effectively mock away stdin and use the ...

2

Passing larger sized data in functions by const &data is a good idea since it does not make a copy. Note that when a parameter is passed by const&, the extra cost dereferencing and fewer opportunities for compile optimizing. You should do this typically when the data is large in size From your next() function int next() { int curr_next =...

2

Avoid storing redundant data in classes I see variables like these in class simulation: std::string robots_ip_string; std::string paths_ip_string; std::string nodes_ip_string; ... Usually, repeating the name of the type in the name of a variable is unnecessary, so at first sight I would say: why not just call them robots_ip, paths_ip, and so on? However, a ...

2

Given that your array is a simple list of uniform type, you might see some small benefit in switching to https://docs.python.org/3.8/library/array.html , which is built specifically for this kind of thing. It's a compromise that uses built-ins without needing to install Numpy.

2

If you instrument your code with some strategically place print statements, you will see that there is some repeated computations going on. In the second test case when processing the clause X2 v ~X3, the set {'X1', 'X2'} gets added to mySets twice. When processing the clause X3 v ~X1, the set {'X3', 'X1', 'X2'} gets added to mySets three times. For large ...

2

I re-wrote your solution to use more typical Clojure features. When you are looping over data and need to keep track of accumulated state, it is hard to beat loop/recur. A first example: (ns tst.demo.core (:use clojure.test)) (defn breaking-records [scores] ; this loop has 5 variables. Init all of them (loop [low (first scores) ...

Only top voted, non community-wiki answers of a minimum length are eligible