# >solved in 10 minutes. And they call this medium

>solved in 10 minutes
And they call this medium

1. 2 weeks ago
Anonymous

reverse polish?
awruk

• 2 weeks ago
Anonymous

Dunno use a stack or something

fpbp
kek

Many CS grads will have encountered this exact question before, because evaluating postfix expressions is a very common example given when teaching stacks. So it's mainly testing whether you remember the general idea ("push operands to the stack, when you encounter an operator it's time to pop the last couple operands and do something to them"). If you've never encountered it before and still solved it in 10min, that's quite impressive.

If you want a good challenge (which will definitely take longer than 10mins), write an infix parser that can handle realistic human input. Think implicit multiplication, distinguishing negation from subtraction, tolerating slightly malformed input, etc.

>will not (can not) solve the problem

• 2 weeks ago
Anonymous

• 2 weeks ago
Anonymous

> Stachu Jones
based.

• 2 weeks ago
Anonymous

invading russia AND germany?

2. 2 weeks ago
Anonymous

Dunno use a stack or something

3. 2 weeks ago
Anonymous

Many CS grads will have encountered this exact question before, because evaluating postfix expressions is a very common example given when teaching stacks. So it's mainly testing whether you remember the general idea ("push operands to the stack, when you encounter an operator it's time to pop the last couple operands and do something to them"). If you've never encountered it before and still solved it in 10min, that's quite impressive.

If you want a good challenge (which will definitely take longer than 10mins), write an infix parser that can handle realistic human input. Think implicit multiplication, distinguishing negation from subtraction, tolerating slightly malformed input, etc.

• 2 weeks ago
Anonymous

the simplest way to solve this (for me) was to use this algorithm
https://en.wikipedia.org/wiki/Shunting-yard_algorithm
to convert from infix to postfix notation and then use my already written parser

• 2 weeks ago
Anonymous

Also known as a stack.

• 2 weeks ago
Anonymous

ok?

• 2 weeks ago
Anonymous

ok

• 2 weeks ago
Anonymous

Why waste your time reinventing the "not even a wheel"? Focus on general unsolved problems, if they are too hard then go learn about them, acquire the requisite knowledge and talk to people about them. You will learn far more, far faster than leetcode.

4. 2 weeks ago
Anonymous

function rpn(input, stack) {
if(input.length == 0) {
return stack[0];
}
switch(input[0]){
case "+":
case "-":
case "*":
case "/": return rpn(input.slice(1), [eval(`Math.trunc(stack[1]\${input[0]}stack[0])`), ...stack.slice(2)]);
default: return rpn(input.slice(1), [Number(input[0]),...stack]);
}
}

console.log( rpn( "10 6 9 3 + -11 * / * 17 + 5 +".split(" "), []));

>but you shouldn't use eval
Fuck you.

• 2 weeks ago
Anonymous

Forget eval mods ought to ban you for javascript

• 2 weeks ago
Anonymous

I only use the browser's console so fuck you too.

• 2 weeks ago
Anonymous

>solved before even entering the thread
it's over for OP
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
for c in tokens:
if c in "+*/-":
right = stack.pop()
left = stack.pop()
if c == "+":
stack.append(left + right)
elif c == "-":
stack.append(left - right)
elif c == "*":
stack.append(left * right)
else:
stack.append(math.trunc(left/right))

else:
stack.append(int(c))
return stack.pop()

>not using handlers for operands
Don't call us, we'll you

• 2 weeks ago
Anonymous

cope

• 2 weeks ago
Anonymous

How is this cope. That's what I'd expect as an interviewer

• 2 weeks ago
Anonymous

that's beyond the scope of this problem and also you don't conduct interviews.

• 2 weeks ago
Anonymous

SIR

5. 2 weeks ago
Anonymous

>10 minutes
NGMI

6. 2 weeks ago
Anonymous

Solved it in 5 minutes, then debugged my truncate method for 15. Gave up and used operator.truediv

7. 2 weeks ago
Anonymous

Is this just a stack?

• 2 weeks ago
Anonymous

It was just a stack.
Had to debug the division a bit but very simple.

class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
def GetFromStack():
return(stack.pop(), stack.pop())

for e in tokens:
if e == "+":
b,a = GetFromStack()
stack.append(a+b)
elif e == "*":
b,a = GetFromStack()
stack.append(a*b)
elif e == "/":
b,a = GetFromStack()
stack.append(int(a/b))
elif e == "-":
b,a = GetFromStack()
stack.append(a-b)
else:
stack.append(int(e))

return stack.pop()

8. 2 weeks ago
Anonymous

>solved before even entering the thread
it's over for OP
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
for c in tokens:
if c in "+*/-":
right = stack.pop()
left = stack.pop()
if c == "+":
stack.append(left + right)
elif c == "-":
stack.append(left - right)
elif c == "*":
stack.append(left * right)
else:
stack.append(math.trunc(left/right))

else:
stack.append(int(c))
return stack.pop()

• 2 weeks ago
Anonymous

Python have types now?

• 2 weeks ago
Anonymous

Of course Python has types.
You just don't have to define it when creating a variable.

• 2 weeks ago
Anonymous

Yes but they are ignored by the compiler. Types only exist for IDEs

• 2 weeks ago
Anonymous

This is a perfect example of class being completely useless. I often see Pythonfags do excessive "OOP" like this, why does it happen?

• 2 weeks ago
Anonymous

when you do a leetcode solution in python it autofills in a class for you and you have to submit your solution as a class

• 2 weeks ago
Anonymous

Oh yuck, well at least it wasn't anon being retarded

• 2 weeks ago
Anonymous

Why did you create a class just to house a function ?

the default leetcode template has both the class and the function definition. the class is instantiated during evaluation.

• 2 weeks ago
Anonymous

Why did you create a class just to house a function ?

9. 2 weeks ago
Anonymous

>iterate until find non-numeric value
>use current index to gather current value and previous two values
>use "if" statements to perform correct arithmetic (ex: if x == "*")
>assign result to current index
>pop previous two indices
>restart iteration from current index minus two (due to popped indices)
fairly simple solve

• 2 weeks ago
Anonymous

This is what I would do too!
Is there a better solution?

10. 2 weeks ago
Anonymous

ngl a lot of the medium difficulty questions will throw some weird math trivia into the mix (like the "product of all except self"), this one seems like it should be easy difficulty but maybe that's just because i've had to make an RPN calculator before.

11. 2 weeks ago
Anonymous

it’s leetcode
it’s designed for normies who are shit at coding, to get them up to speed for interviews
if you are not able to solve every easy problem in 10 minutes, every medium problem in 15 minutes, and every advanced problem in 1 hour, you’re a shit programmer

• 2 weeks ago
Anonymous

>15 mins for you
I see

• 2 weeks ago
Anonymous

Meh. It's like training for arm wrestling.

12. 2 weeks ago
Anonymous

impl Solution {
pub fn eval_rpn(tokens: Vec<String>) -> i32 {
let mut stack = vec![];

for t in tokens {
let op = match &*t {
"-" => std::ops::Sub::sub,
"*" => std::ops::Mul::mul,
"/" => std::ops::Div::div,
_ => {
stack.push(t.parse().unwrap());
continue;
}
};

let r = stack.pop().unwrap();
let l = stack.pop().unwrap();
stack.push(op(l, r));
}

stack.pop().unwrap()
}
}

• 2 weeks ago
Anonymous

>&*t
fucking hell

13. 2 weeks ago
Anonymous

The first stack problem you encounter is a medium level problem.
But once you have done a stack problem it's just "oh look, a stack problem".

14. 2 weeks ago
Anonymous

whoever read K&R will find this easy

15. 2 weeks ago
Anonymous

>solved in 10 minutes
ngmi

16. 2 weeks ago
Anonymous

10 minutes HAHAHAHA this is simply
dc

17. 2 weeks ago
Anonymous

"Medium" just means something is neither rare nor well done.

18. 2 weeks ago
Anonymous

here's dugrasoft™ approved solution

static int Solve(params string[] tokens)
{
Stack<int> stack = new();

foreach (string token in tokens)
{
Func<int, int, int>? func = token switch
{
"+" => (a, b) => a + b,
"-" => (a, b) => a - b,
"*" => (a, b) => a * b,
"/" => (a, b) => a / b,
_ => null,
};

if (func is null)
{
stack.Push(int.Parse(token));
}
else
{
int b = stack.Pop();
int a = stack.Pop();
int result = func(a, b);

stack.Push(result);
}
}

return stack.Pop();
}

19. 2 weeks ago
Anonymous

In C#:
public int EvalRPN(string[] tokens)
{
var s = new Stack<int>();

foreach(var t in tokens)
{
s.Push(
t switch {
"+" => s.Pop() + s.Pop(),
"-" => Sub(s.Pop(), s.Pop()),
"*" => s.Pop() * s.Pop(),
"/" => Div(s.Pop(), s.Pop()),
_ => int.Parse(t)
}
);
}

return s.Pop();

// Not commutative
int Sub(int a, int b) => b - a;
int Div(int a, int b) => b / a;
}

20. 2 weeks ago
Anonymous

It took me waaaay longer than I expected. Initially, I quickly solved it with this approach
(defun plus (stack)
(push (+ (pop stack) (pop stack)) stack))
;;; ...
(defun solve (lst &optional stack)
(cond ((null lst) (pop stack))
((string-equal (first lst) "+") (solve (rest lst) (plus stack)))
((string-equal (first lst) "-") (solve (rest lst) (minus stack)))
((string-equal (first lst) "*") (solve (rest lst) (times stack)))
((string-equal (first lst) "/") (solve (rest lst) (divide stack)))
(t (solve (rest lst) (cons (parse-integer (first lst)) stack)))))

but I was not happy. Thus, I spent a lot of time trying to make it neat with a dispatch macro to generate many 'cond' conditions. It turns out you can't write a macro to do that (i.e., return two or more forms instead of a list of forms) so I tried some other approach until generic functions came to my mind. I was trying to make generic functions dispatch on strings, but apparently it is not trivial (e.g., metaobject protocol or something) and maybe not even entirely possible. So I settle down for this
(defparameter *stack* '())

(defun operation (op n)
(push (apply op (loop for i from 1 to n collect (pop *stack*))) *stack*))

(defgeneric dispatch (x)
(:method ((x real)) (push x *stack*))
(:method ((x (eql '+))) (operation #'+ 2))
(:method ((x (eql '-))) (operation #'- 2))
(:method ((x (eql '*))) (operation #'* 2))
(:method ((x (eql '/))) (operation #'/ 2)))

(defun solve (lst)
(loop for elt in lst do (dispatch (read-from-string elt)))
(pop *stack*))

(solve '("2" "1" "+" "3" "*")) ; => 9
(solve '("4" "13" "5" "/" "+")) ; => 57/13 (4.3846154)

• 2 weeks ago
Anonymous

It looks a bit like LISP. Couldn't you just do something like this (Racket-flavour pseudo-LISP):
(define (solve inp acc)
(if (null inp) (car acc) (
(let [op (car inp)] [a (cadr acc)] [b (car acc)])
(solve (cdr inp) (cons (cond
[(= '+' op) (+ a b)]
...
[else (char->number op)])) inp
)))

(inp is an input list, acc is a list used as stack.)

• 2 weeks ago
Anonymous

Not sure what you mean, can you elaborate more?

• 2 weeks ago
Anonymous

It looks a bit like LISP. Couldn't you just do something like this (Racket-flavour pseudo-LISP):
(define (solve inp acc)
(if (null inp) (car acc) (
(let [op (car inp)] [a (cadr acc)] [b (car acc)])
(solve (cdr inp) (cons (cond
[(= '+' op) (+ a b)]
...
[else (char->number op)])) inp
)))

(inp is an input list, acc is a list used as stack.)

different anon here, yeah you can just funcall it
(defun apply-operator (op stack)
(cons (truncate (funcall op (cadr stack) (car stack))) (nthcdr 2 stack)))

(defun solve (input)
(let ((list (mapcar #'read-from-string input))
(stack nil))
(dolist (x list (car stack))
(if (numberp x) (push x stack) (setf stack (apply-operator x stack))))))

• 2 weeks ago
Anonymous

Is it as flexible as

It took me waaaay longer than I expected. Initially, I quickly solved it with this approach
(defun plus (stack)
(push (+ (pop stack) (pop stack)) stack))
;;; ...
(defun solve (lst &optional stack)
(cond ((null lst) (pop stack))
((string-equal (first lst) "+") (solve (rest lst) (plus stack)))
((string-equal (first lst) "-") (solve (rest lst) (minus stack)))
((string-equal (first lst) "*") (solve (rest lst) (times stack)))
((string-equal (first lst) "/") (solve (rest lst) (divide stack)))
(t (solve (rest lst) (cons (parse-integer (first lst)) stack)))))

but I was not happy. Thus, I spent a lot of time trying to make it neat with a dispatch macro to generate many 'cond' conditions. It turns out you can't write a macro to do that (i.e., return two or more forms instead of a list of forms) so I tried some other approach until generic functions came to my mind. I was trying to make generic functions dispatch on strings, but apparently it is not trivial (e.g., metaobject protocol or something) and maybe not even entirely possible. So I settle down for this
(defparameter *stack* '())

(defun operation (op n)
(push (apply op (loop for i from 1 to n collect (pop *stack*))) *stack*))

(defgeneric dispatch (x)
(:method ((x real)) (push x *stack*))
(:method ((x (eql '+))) (operation #'+ 2))
(:method ((x (eql '-))) (operation #'- 2))
(:method ((x (eql '*))) (operation #'* 2))
(:method ((x (eql '/))) (operation #'/ 2)))

(defun solve (lst)
(loop for elt in lst do (dispatch (read-from-string elt)))
(pop *stack*))

(solve '("2" "1" "+" "3" "*")) ; => 9
(solve '("4" "13" "5" "/" "+")) ; => 57/13 (4.3846154)

tho? Try to implement operator ! to compute the factorial.

• 2 weeks ago
Anonymous

yeah you can just add a cond and add operators as many as you want
(defun ! (n)
(if (zerop n) 1 (* n (! (1- n)))))

(defun apply-operator (op stack)
(cons (cond ((equal '! op) (funcall op (pop stack)))
(t (truncate (apply op (reverse (list (pop stack) (pop stack)))))))
stack))

(defun solve (input)
(let ((list (mapcar #'read-from-string input))
(stack nil))
(dolist (x list (car stack))
(if (numberp x) (push x stack) (setf stack (apply-operator x stack))))))

21. 2 weeks ago
Anonymous

Bruh bruh, we fr get that you found leetcode problems.
But please stop making threads for the ones youre stuck on..

22. 2 weeks ago
Anonymous

>anon posts picture and claims he solved it in 10 minutes
>without proof
>other anons post solutions
Was this just a clever trick by OP to have other anons solve this for him?

• 2 weeks ago
Anonymous

OP can suck my dick I just want to flex

• 2 weeks ago
Anonymous

This is precisely how LULZ works.
>Ignored and saged.
>make thread arrogantly claiming solution to problem you cant actually solve
>retards come in to prove their smarticles
Pottery

23. 2 weeks ago
Anonymous

>don't even have to tokenise it yourself
who writes this shit?

24. 2 weeks ago
Anonymous

>It's another episode of insecure neets praying to God they're smart

25. 2 weeks ago
Anonymous

Befunge basically already is a RPN calculator so this was easy (or supposed to be), since I can just use its stack directly and paste the operators in the program code. But there's some caveats.

Integer input is kind of stupid in Befunge so you'll need to prefix each integer with "#+" or "#-". stdin for example 3 (which I used in the webm) looks like:
#+10 #+6 #+9 #+3 + #-11 * / * #+17 + #+5 +

Spaces and newlines are also pasted in the code as operations but these are interpreted as NOP's so that's fine.

Befunge doesn't specify how the division operator truncates, so when I wrote the interpreter I went with Crystal's default behaviour of flooring. So that's why the result is 12 instead of 22.
I'm not going to bother fixing it because in 15 years of programming this is the first time I've actually needed this division behavior.

26. 2 weeks ago
Anonymous

meh, not even a multiline solution

*(){\$[+//y=:!s:"*/+-"!(*;{(-x)!y};+;-);(2_x),(s y).2#x;(`I\$y),x]}/

27. 2 weeks ago
Anonymous

these are good threads op keep it up!!! masking an actually good general with shitposting bait

• 2 weeks ago
Anonymous

i agree. every time i click the thread wanting to call OP a retard and i end up solving the problem

• 2 weeks ago
Anonymous

It's a good way to filter bots

28. 2 weeks ago
Anonymous

I've been a software dev for five years, 15 years of programming experience. I have written a kernel, compilers, serializers, a shitton of drivers, designed communication protocols in security critical systems. I seriously suck at leetcode.

• 2 weeks ago
Anonymous

I blame the problem descriptions they use. Most of them are so badly written that it makes easy problems look like medium ones.

• 2 weeks ago
Anonymous

this, they're either doing it on purpose or it's just pajeets writing them

• 2 weeks ago
Anonymous

This is cope, they're well written. They are just hard in general, and require knowledge of DSA to solve.

• 2 weeks ago
Anonymous

>t. pajeet leetcode grinder

• 2 weeks ago
Anonymous

Go ahead, name a single problem.

• 2 weeks ago
Anonymous

this, they're either doing it on purpose or it's just pajeets writing them

This is cope, they're well written. They are just hard in general, and require knowledge of DSA to solve.

I don't think they are poorly written, they are just catering to very specific kind of autism that not every programmer has. I can get okay at them if I grind leetcode, I did so the last time I needed to get a new job, but I just find it hard to stay motivated. The thing is, I just do not give a fuck. It's like advent of code. Yeah it's neat and all but honestly I just do not give a shit. It's like those "what if you had a fox and sheep and a bag of salad on one side of the river..." kind of question, I physically cannot care about these kinds of questions.

29. 2 weeks ago
Anonymous

>SIR please solve this LC and make it a Spring boot webservice
>start to focus on problem
>SIR SIR we practice pair programming here
>constantly interrupted
>still haven't gotten to read the problem
>setup the TDD SIR
>have everything setup
>finally read 3/4 the problem statement
>SIR HOW WOULD YOU SOLVE THIS PROBEM
>still don't get to read the fucking problem
>pull out notebook so i'm not juggling shit in my head
>SIR WHY AREN'T YOU SPEAKING?

• 2 weeks ago
Anonymous

How much time did they give you ?

30. 2 weeks ago
Anonymous

We had this thread yesterday. No one cares.

• 2 weeks ago
Anonymous

>No one cares
>45 posters

31. 2 weeks ago
Anonymous

The difficulty ratings are intended for learn2coders who didn't go to college.

It's very simple:
The easies are for brainlets; zero thinking required. The mediums are for people who can work their way through a problem, but lack a formal education. Hards sometimes require actual programming knowledge. If a self taught coder stumbles into a hard, it can take hours for them to complete it

32. 2 weeks ago
Anonymous

This took me longer than 10 minutes, but only because I kept getting 12 for Example 3 and didn't understand why. Eventually I realized it's because div in haskell truncates toward negative infinity, and I needed to use quot which truncates toward 0.

solution :: [String] -> Maybe Int
solution = eval [] where
eval [s] [] = Just s
eval (x:y:s) ("+":rest) = eval (y+x:s) rest
eval (x:y:s) ("-":rest) = eval (y-x:s) rest
eval (x:y:s) ("*":rest) = eval (y*x:s) rest
eval (x:y:s) ("/":rest) = do { if x == 0 then Nothing else Just (); eval (y `quot` x:s) rest }
eval s (str:rest) = do { n <- readMaybe str; eval (n:s) rest }
eval _ _ = Nothing

33. 2 weeks ago
Anonymous

i see no one has solved it in the greates programming language yet

#include <stdio.h>
#include <stdlib.h>

typedef struct node{
int num;
struct node *next;
} node;

typedef struct{
} fifo;

node *createNode(int num){
node *nn = malloc(sizeof(node));
nn->num = num;
nn->next = NULL;
return nn;
}

fifo *createFifo(){
fifo *nf = malloc(sizeof(fifo));
return nf;
}

void insert(fifo *f, int num){
node *n = createNode(num);
node *t = f->head;
while(t->next != NULL)
t = t->next;
t->next = n;
}else{
}
}

int get(fifo *f){
node *t = f->head->next;
int r = f->head->num;
return r;
}
return -1;
}

int main(){

char *tokens = "21+3*";
int i = 0;
fifo *f = createFifo();

while(tokens[i] != ''){
if(tokens[i] >= '0' && tokens[i] <= '9')
insert(f, tokens[i]-'0');
else{
int r;
switch(tokens[i]){
case '+':
r = get(f) + get(f);
insert(f, r);
break;
case '-':
r = get(f) - get(f);
insert(f, r);
break;
case '*':
r = get(f) * get(f);
insert(f, r);
break;
case '/':
r = get(f) / get(f);
insert(f, r);
break;
default:
printf("Unknown symbol %cn", tokens[i]);
break;
}
}
++i;
}

i = 0;
printf("Result of operationnt"");
while(tokens[i])
printf("%c ", tokens[i++]);
printf("b"n: %d", get(f));

return 0;
}

• 2 weeks ago
Anonymous

greatest*

34. 2 weeks ago
Anonymous

i've seen a few forth shills around here lately, and this looks like it would be right up their alley, so can any forth chads come in here and show us how it's done?

• 2 weeks ago
Anonymous

bumping for the Forth solution

• 2 weeks ago
Anonymous

Forthanons? i thought it was the most powerful language?
@forth_developers @/g/

• 2 weeks ago
Anonymous

I don't see any reason to solve that in forth or any other language. I already implemented my own forth so why would I want to solve this less general case of it.
With forth the only problem is how to execute the wanted "forth primitive" for each token provided. Assuming that the tokens are provided via an array of string pointers, then you could just parse a string check if number(push to stack) if not then find the word(function) with same name as the string content and execute that. So probably like max 25 lines of code for a novice like me.
Alternatively you could just separate each token with some white space and pass that to a forth interpreter followed by the token ".".

35. 2 weeks ago
Anonymous

I'm proud of this one
def calc(toks):
stack = []
stack.extend(
op(stack.pop(), stack.pop())
if (
op := {
"*": int.__rmul__,
"/": int.__rfloordiv__,
"-": int.__rsub__,
}.get(tok)
)
else int(tok)
for tok in toks
)
return stack.pop()

36. 2 weeks ago
Anonymous

yes

37. 2 weeks ago
Anonymous

>do you know what a stack is?

38. 2 weeks ago
Anonymous

n-word, if you needed 10 minutes for this, you're borderline retarded