Top
Best
New

Posted by mpweiher 20 hours ago

Many hard LeetCode problems are easy constraint problems(buttondown.com)
502 points | 434 commentspage 2
ripped_britches 19 hours ago|
I would be blown away if a candidate solved it using DP and then said “but let me show you how to use a constraint solver”. Immediate hire.
cadamsdotcom 5 hours ago||
This. Jump through their hoops first.
henry2023 13 hours ago||
+1
RomanPushkin 16 hours ago||
- Constraint solvers? That's a nice concept, I heard about this once. However, for the purposes of the interview, let's just write some Python code, I wanna see your way of thinking...

(I think it's almost impossible to convince your interviewer into constraint solvers, while the concept itself is great)

aaronblohowiak 16 hours ago||
import z3
cerved 13 hours ago||
from ortools.sat.python import cp_model
henry2023 13 hours ago||
Have you ever tried or this is your assumption of what the interviewer would say.
itissid 18 hours ago||
Long time ago, just for fun, I wrote a constraint solver problem that could figure out which high yield banks to put money into that were recommended on doctor of credit(https://www.doctorofcredit.com/high-interest-savings-to-get/) based on <= `X` money and <= `Y` # of transactions on debit cards maximize the yield and other constraints(boolean and real valued)

I played it for a while when interest rates were really low and used the thing for my own rainy day savings(I did get tired changing accounts all the time)

toomuchtodo 18 hours ago|
Repo?
drob518 18 hours ago||
SAT, SMT, and constraint solvers are criminally underutilized in the software industry. We need more education about what they are, how they work, and what sorts of problems they can solve.
LegionMammal978 18 hours ago||
At least personally, I've been very underwhelmed by their performance when I've tried using them. Usually past a few dozen variables or so is when I start hitting unacceptable exponential runtimes, especially for problem instances that are unsatisfiable or barely-satisfiable. Maybe their optimizations are well-suited for knapsack problems and other classic OR stuff, but if your problem doesn't fit the mold, then it's very hit-or-miss.
zaxioms 6 hours ago|||
I'm surprised to hear this. Modern SAT solvers can easily handle many problems with hundreds of thousands of variables and clauses. Of course, there are adversarial problems where CDCL solvers fail, but I would be fascinated if you can find industrial (e.g. human written for a specific purpose) formulas with "dozens of variables" that a solver can't solve fairly quickly.
LegionMammal978 4 hours ago||
One thing that I spent a particularly long time trying to get working was learning near-minimum-size exact languages from positive and negative samples. DFAMiner [0] has a relatively concise formulation for this in terms of variables and clauses, though I have no way to know if some other reformulation would be better suited for SAT solvers (it uses CaDiCaL by default).

It usually starts taking a few seconds around the ~150-variable mark, and hits the absolute limit of practicality by 350–800 variables; the number of clauses is only an order of magnitude higher. Perhaps something about the many dependencies in a DFA graph puts this problem near the worst case.

The annoying thing is, there do seem to be heuristics people have written for this stuff (e.g., in FlexFringe [1]), but they're all geared toward probabilistic automata for anomaly detection and similar fuzzy ML stuff, and I could never figure out how to get them to work for ordinary automata.

In any case, I eventually figured out that I could get a rough lower bound on the minimum solution size, by constructing a graph of indistinguishable strings, generating a bunch of random maximal independent sets, and taking the best of those. That gave me an easy way to filter out the totally hopeless instances, which turned out to be most of them.

[0] https://github.com/liyong31/DFAMiner

[1] https://github.com/tudelft-cda-lab/FlexFringe

cerved 13 hours ago||||
I've worked on a model with thousands of variables and hundreds of thousands of parameters with a hundred constraints. There are pitfalls you need to avoid, like reification, but it's definitely doable.

Of course, NP hard problems become complex at an exponential rate but that doesn't change if you use another exact solving technique.

Using local-search are very useful for scaling but at the cost of proven optimality

j2kun 17 hours ago||||
I think this hits the nail on the head: performance is the obstacle, and you can't get good performance without some modeling expertise, which most people don't have.
drob518 17 hours ago||
Hence my call for more education.
js8 17 hours ago||||
I wish I knew better how to use them for these coding problems, because I agree with GP they're underutilized.

But I think if you have constraint problem, that has an efficient algorithm, but chokes a general constraint solver, that should be treated as a bug in the solver. It means that the solver uses bad heuristics, somewhere.

LegionMammal978 16 hours ago||
I'm pretty sure that due to Rice's theorem, etc., any finite set of heuristics will always miss some constraint problems that have an efficient solution. There's very rarely a silver bullet when it comes to generic algorithms.
zaxioms 6 hours ago|||
Rice's theorem is about decidability, not difficulty. But you are right that assuming P != NP there is no algorithm for efficient SAT (and other constraint) solving.
sigbottle 15 hours ago|||
I think they're saying that the types of counter-examples are so pathological in most cases that if you're doing any kind of auto-generation of constraints - for example, a DSL backed by a solver - should have good enough heuristics.

Like it might even be the case that certain types of pretty powerful DSLs just never generate "bad structures". I don't know, I've not done research on circuits, but this kind of analysis shows up all the time in other adjacent fields.

LegionMammal978 13 hours ago||
Idk, I also thought so once upon the time. "Everyone knows that you can usually do much better than the worst case in NP-hard problems!" But at least for the non-toy problems I've tried using SAT/ILP solvers for, the heuristics don't improve on the exponential worst case much at all. It's seemed like NP-hardness really does meet the all-or-nothing stereotype for some problems.

Your best bet using them is when you have a large collection of smaller unstructured problems, most of which align with the heuristics.

sigbottle 13 hours ago|||
> Your best bet using them is when you have a large collection of smaller unstructured problems, most of which align with the heuristics.

Agreed. An algorithm right now in our company turns a directed graph problem, which to most people would seem crazy, into roughly ~m - n (m edges, n nodes) SAT checks that are relatively small. Stuffing all the constraints into an ILP solver would be super inefficient (and honestly undefined). Instead, by defining the problem statement properly and carving out the right invariants, you can decompose the problem to smaller NP-complete problems.

Definitely a balancing act of design.

drob518 13 hours ago|||
For some problems, there is not much you can do. But for many, it works.
drob518 17 hours ago|||
Well, they aren’t magic. You have to use them correctly and apply them to problems that match how they work. Proving something is unsat is worst case NP. These solvers don’t change that.
LegionMammal978 17 hours ago||
Of course they aren't magic, but people keep talking about them as if they're perfectly robust and ready-to-use for any problem within their domain. In reality, unless you have lots of experience in how to "use them correctly" (which is not something I think can be taught by rote), you'd be better off restricting their use to precisely the OR/verification problems they're already popular for.
drob518 16 hours ago||
Hence my statement about education. All tools must be used correctly in their proper domain, that is true. Don’t try to drive screws with a hammer. But I'm curious what problems you tried them on and found them wanting and what your alternative was? I actually find that custom solutions work better for simple problems and that solvers do a lot better when the problem complexity grows. You’re better off solving the Zebra puzzle and its ilk with brute force code, not a solver, for instance.
loeg 18 hours ago||
In what way? They're useful for toy problems like this but they're very slow on larger problems.
drob518 17 hours ago|||
SAT solvers are used daily to generate solutions for problems that have literally millions of variables. So, what you said is just wrong on the face. Yes, some talented people can write custom code that solves specific problems faster than a general purpose solver, particularly for easy special cases of the general problem, but most of the time that results in the programmer recreating the guts of a solver customized to a specific problem. There’s sort of a corollary of Greenspun’s Tenth Rule that every sufficiently complicated program also contains an ad hoc, informally-specified, bug-ridden, slow-implementation of half of a SAT or SMT solver.
sigbottle 16 hours ago||
I mean right tool for the right job. Plenty of formulations and problems (our job has plenty of arbitrarily hard graph algorithms) that have 90% of the problem just being a very clever reduction with nice structure.

Then the final 10% is either NP hard, or we want to add some DSL flexibility which introduces halting problem issues. Once you lower it enough, then comes the SMT solvers.

cerved 13 hours ago|||
Define large. We've written model which solves real business issues in 8K lines of MiniZinc and it wasn't slow.

The conventional wisdom is the larger you make an NP hard problem, the slower is going to get. Irregardless of algorithm.

krosaen 17 hours ago||
I find this post interesting independent of the question of whether leetcode problems are a good tool for interviews. It's: here are some kinds or problems constraint solvers are useful for. I can imagine a similar post about non-linear least squared solvers like ceres.
smj-edison 16 hours ago|
Yeah, especially for learning how to use a solver!

> Most constraint solving examples online are puzzles, like Sudoku or "SEND + MORE = MONEY". Solving leetcode problems would be a more interesting demonstration.

He's exactly right about what tutorials are out there for constraint programming (I've messed around with it before, and it was pretty much Sudoku). Having a large body of existing problems to practice against is great.

j2kun 17 hours ago||
> The real advantage of solvers, though, is how well they handle new constraints.

Well said. One of the big benefits of general constraint solvers is their adaptability to requirements changes. Something I learned well when doing datacenter optimization for Google.

deepsun 4 hours ago||
As an interviewer, I gave one pretty simple task (people solved it in as little as 8 minutes), wasn't using any real CS, even though I'm good at it.

The reason was that aboint 70% of candidates couldn't write a simple loop -- to filter those out. The actual solution didn't matter much, I gave a binary decision. The actual conversation matters more.

Tade0 2 hours ago|
This. Main point of giving candidates CS problems was always to weed out those who couldn't program at all, but somehow were still in the industry. I worked with such people - it's unpleasant.

Somehow someone figured that giving harder problems should result in better candidates. Personally, despite having passed most of the tests I've been subjected to, I don't see the connection.

qnleigh 19 hours ago||
I agree with the other comments here that using a constraint solver defeats the purpose of the interview. But this seems like a good case for learning how to use a constraint solver! Instead of spending hours coding a custom solution to a tricky problem, you could use a constraint solver at first and only write a custom solution if it turns out to be a bottleneck.
tannhaeuser 12 hours ago||
Here's an easy ad-hoc Prolog program for the first problem:

    % Given a set of coin denominations,
    % find the minimum number of coins
    % required to make change.
    % IE for USA coinage and 37 cents,
    % the minimum number is four
    % (quarter, dime, 2 pennies).
    num(0). num(1). num(2).
    num(3). num(4). num(5).
    ?- num(Q), num(D), num(P),
       37 is Q * 25 + D * 10 + P
You can just paste it into [1] to execute in the browser. Using 60 as target sum is more interesting as you can enumerate over two solutions.

(Posting again what I already posted two days ago [2] here)

[1]: https://quantumprolog.sgml.net/browser-demo/browser-demo.htm...

[2]: https://news.ycombinator.com/item?id=45205030

skydhash 12 hours ago||
I've actually used pseudo-prolog to explain how to solve leetcode problems to a friend. Write the facts, then write the constraints, and then state your problem. Close to the last part, they've already understood how to solve it, or at least how to write the program that can answer the question.
6gvONxR4sf7o 12 hours ago||
Of course, the challenge is that the next question after solving a leetcode problem is often to explain and optimize the performance characteristics, which in prolog can get stupidly hairy.
theendisney 6 hours ago|

   coins = [100,50,25,10,5,1]
   change = 1234;
   result = [0,0,0,0,0,0];
   for(i=0:i<coins.length;i++){
     while(change>coins[i]){
       result[i]++;
       change-=coins[i];
     }
   }
   //[12,0,1,1,4]
Coudnt help myself sorry
efortis 4 hours ago|
me neither

  function coin_change(change) {
    const coins = [25, 10, 5, 1]
    for (const coin of coins) {
      const n = change / coin | 0
      change -= n * coin
      console.log(coin, n)
    }
  }

  coin_change(25+10+5+1)
More comments...