Wednesday, December 30, 2015

Equalize the buckets

You start with two buckets of water. First bucket has $x$ litres and the second bucket has $y$ litres. Both have enough capacity to hold $x+y$ litres.

Now you do the following:

You take the bucket with the larger amount of water and from that pour water into the other bucket so that the other bucket has double the water.

So if $x \lt y$, then we go from $(x,y)$ to $(2x, y-x)$.

You keep doing this till the buckets have an equal amount of water. Note that in some cases, you will loop indefinitely.

For what initial $(x,y)$ will you be able to equalize the buckets, and not loop indefinitely?

Friday, December 18, 2015

All is not lost

This is a hand from a Swiss teams in the Seattle area.

You are South and hold A9, AKxxxx, xxx, xx. You hear opponents having a canape auction to 4S, LHO declaring and showing 4+ spades and equal or longer diamonds.

Partner leads the HT and you see


IMPS
E/W 




 East
♠ JTxxx
♥ Jxx
♦ Axx
♣ AJ
 South
♠ A9
♥ AKxxxx
♦ xxx
♣ xx


The lead is either a singleton or doubleton. You have 3 tricks (SA and HAK).

If the lead is a singleton you can easily get a heart ruff for the setting trick.

If the lead is not a singleton, where is your fourth trick coming from? You have one easy option: partner has the Qx of spades and can promote his Q on the third round of hearts.

What if partner does not have the Qx of spades? Is there any other option? Partner could have the KQ of clubs, in which case you need to shift to clubs before your SA is knocked out. [Partner might have led the CK, yes.]

So the defense is really simple, win the first trick, cash the second heart to confirm is partner has a singleton (in which case, give a ruff immediately).

If partner has a doubleton heart, shift to a club. When you come in with the spade A, you can decide whether to play partner for the Qx of spades or the club. [Could partner figure out your problem and play the club in such a way as to make it clearer to you?]

But in your excitement in setting up a potential club trick, you win the first trick, and shift to a club immediately without cashing the second heart!

Declarer plays the CQ from hand,  low from partner and J from dummy. Next declarer plays a diamond to dummy  and cashes the CA throwing a heart! [You are too shocked to notice partner's cards, if you wanted to know...]

Now declarer plays a low spade. You go up with the A and cash your second heart, declarer playing the Q. Oops. Partner had a singleton heart all along, and you have botched up a sure shot defense.

Could partner still have the SQ which you can promote? Unlikely, declarer played a low spade instead of the J or T and you hold the 9, so looks like declarer probably has the KQ of spades.

But all is not lost.

Do you want to know what partner played on the second heart? Partner played a diamond.

Looks like declarer started with a 4=3=5=1 hand. He played a D to the A already, and partner threw a diamond on the second heart.

Give partner a diamond ruff! You partner defended accurately (not covering the CQ and throwing a diamond), giving you a chance to recover.

Don't let your previous mistake stop you from recovering. Alas, that is easier said than done.

Friday, December 11, 2015

Pens and Caps [Solution]

Kostub has agreed to post his solution to the business card problem, so I will be breaking order (What? There was one?) and posting a solution to the Pens and Caps problem.

The problem:

You have $n$ pens, and $n$ caps for the pens. For every pen, there is exactly one cap that fits. The rest are either loose or tight.

Someone has taken the caps out and jumbled them up. Can you fit the caps on their respective pens, in expected $O(n \log n)$ time?

Solution


You basically do a quicksort!

Choose a cap at random. Now split the pens based on that cap. Smaller pens on one side (cap is loose), larger on the other (cap is tight) and the one that exactly fits is kept aside.

Now you recurse. Any expected time analysis for random pivot based quicksort will work here too.



Saturday, November 21, 2015

Lucky lead

A quick rabbit sketchboard story. [Characters from Bridge in the Menagerie].


RR is holding xx, AKJTxxx, xx, xx, when he hears his RHO Papa, open 1NT. RR bids 3H (showing a 7 card suit), and his LHO (SB), bids 3NT with the air of someone who has a heart stopper, and it becomes the final contract.

While RR is fiddling with his cards and trying to figure out what his latest lead agreement with HH is, the HJ drops on the table. HH, who had been distracting Papa by taking a sandwich off Papa's plate, points to the HJ as SB spreads the dummy.

This is what Papa sees (lead HJ):

IMPS
None 
 SB
♠ AKx
♥ Qxx
♦ Jxxx
♣ xxx

  


 Papa
♠ QJx
♥ xx
♦ AKQx
♣ Axxx

W N E S
1NT
3H3NTPP
P


Papa reasons that RR likely has AJTxxxx or KJTxxxx with RHO holding a singleton honour. As he needs a heart trick to make the contract, the correct play is to play low from dummy.

When the J wins, RR is more surprised than Papa, and proceeds to cash the rest of the heart tricks.

HH remarks that he would have led the HJ too.

Tuesday, November 17, 2015

Pens and Caps

You have $n$ pens, and $n$ caps for the pens. For every pen, there is exactly one cap that fits. The rest are either loose or tight.

Someone has taken the caps out and jumbled them up. Can you fit the caps on their respective pens, in expected $O(n \log n)$ time?

[Solution]

Friday, November 13, 2015

Kostub's business card problem

This is a problem on Kostub Deshmukh's business card (co-founder of math.chat). The premise of math chat is to do math with friends, and the problem is in that spirit.

I will let the business card speak for itself:





If you are having problems with the image, the problem in text:

In a group of 9 mathematicians, each speaks at most 3 languages, and each pair of mathematicians share a language.

Show that at least 5 mathematicians speak the same language.

Note: I haven't solved it myself yet. Perhaps Kostub will post a solution in the comments sometime.

Saturday, October 31, 2015

Lucky 3NT

This is a hand from the Lynwood/Everett regional a long time back, when they were playing handicapped knockouts.

This is a hand from the finals of the KO.

You hold Q32, T82, T852, 987. I don't remember the vulnerabilty (assume None).

Partner opens 1H, you decide to bid a forcing 1NT (hoping to drop partner in 2H), but partner surprises you by bidding 3NT. You decide to pass instead of bidding 4H.

LHO leads a low spade.

You see.

IMPS
None 
 North
♠ AJ3
♥ A9765
♦ K3
♣ AKQ

    


 South
♠ Q32
♥ T82
♦ T852
♣ 987

W N E S
1HP1N
P3NTPP
P

Partner could have opened 2NT. Anyway...

You run the spade to the Q and it wins.

With nothing better to do, you play a heart to the A (LHO following with the J) and a heart back, hoping opponents crash their honours. RHO plays low and LHO wins the second heart with the K.

[Technically, it might have been better to duck the first heart].

LHO now shifts to the DQ. You cover the K, RHO wins the A and leads a low diamond back. You hold your breath, and put in the 8: LHO wins the J. Your DT is now good! Unfortunately, hand entries are scarce.

LHO now plays a club.

Now the play is clear. You cash the top clubs, and play a heart. RHO wins the Q, but now is endplayed into playing a spade or a diamond! Cashing the clubs took away RHO's exit cards. 3NT made.

RHO could have defeated the contract by cashing the HQ before playing the second round of diamonds. That is why ducking the first round of hearts is technically better, as you take away that option.

At the other table opponents were in 4H which had no hope.

We won the event, but only because of a handicap. Me and my partner threw away the next few boards :(

I think they stopped having handicapped tournaments after that. I believe the opponents complained that the handicapping was unfair, and I agree with them. Apart from me, the other three players on my team had won/placed well in national tournaments in India.

The handicaps were based on ACBL masterpoints, and apart from me, none of them were ACBL members (one was just visiting), and I believe we had no clue about seeding points etc.

Thursday, October 29, 2015

Quicksort in log space [Solution]

The problem was to implement in-place quicksort (partitioning by pivoting on first element) in worst case $O(\log n)$ space.

Solution


This is a classic, probably due to Robert Sedgewick.

The absolutely trivial implementation of quicksort looks like

def qsort(arr, L, R):
  if L >= R:
    return
  mid = partition(arr)
  qsort(arr, L, mid)
  qsort(arr, mid+1, R)


Now the two recursive calls are interchangeable and the last one can be made tail recursive.

If we always pick the smaller partition to recurse on, and tail recurse on the larger partition, we will end up only using $O(\log n)$ space!

An implementation might look like (handwaving here)


def qsort(arr, L, R):
  while R > L:
  mid = partition(arr)
  if mid -L < R - mid:
    qsort(arr, L, mid)
    L,R = mid, R
   else:
    qsort(mid, R)
    L,R = L, mid

Note this idea can be used to make recursive binary tree traversals use $O(\log n)$ space, irrespective  of the tree structure, as long we maintain a count of the descendants of each node: recurse on the smaller tree, but tail recurse on the larger one.

Monday, October 26, 2015

Inequality from UW challenge of the week [Solution]

The problem was here.

In brief

$x_i$ are $n$ real numbers such that

$$ \sum _{k=1}^{n} x_i = 0$$

$$ \sum_{k=1}^{n} x_i^2 = 1$$

Show that for some $i,j$,

$$ x_i x_j \le -\frac{1}{n}$$

Solution


The official solution is quite neat.

wlog, assume $x_1 \le x_2 \le \dots \le x_n$.

Now

$$ 0 \le \sum_{k=1}^n (x_k - x_1)(x_n - x_k) = -nx_1x_n - 1$$

(The equality is just gotten from expanding out and using the given identities).

The inequality now follows immediately.

Saturday, October 24, 2015

Misfit 3NT

This is a hand from the recent Bothell Sectional Swiss teams sectional event, near Seattle (where we probably set a record for the worst session ever!).

Red vs White, you hold AKJT8, K, Q65, Q765.

Partner is dealer and opens 1H. RHO bids 2H (Michaels), which you double (willing to penalize RHO), LHO bids 3D, pass, pass to you, and the vulnerability sways you to bid 3NT.

LHO leads the club ten. You see

IMPS
N/S 
 North
♠ 92
♥ AQJ93
♦ 432
♣ A32

    


 South
♠ AKJT8
♥ K
♦ Q65
♣ Q765

W N E S
1H2HX
3DPP3NT
PPP


How will you play?

[Please think about it before reading on]






The lead of CT makes it look like LHO has a spade void and long diamonds and hearts, with RHO having the black suits.

There is great danger in ducking. RHO will win the CK and shoot a diamond through. You will be down immediately.

Assuming LHO has hearts and diamonds, looks like LHO can be caught in some form of an endplay.

Suppose you win and take four rounds of spades (taking the finesse: a good RHO would not cover the 9), and then cash the A (overtaking the K) and Q of hearts.

What 6 cards does LHO come down to? LHO needs to hold onto 2+ hearts. If LHO has come down to AK tight of diamonds, you can exit a diamond. Otherwise you can cash the HJ and exit a heart.

Turns out that LHO indeed had a spade void (as inferred from the lead) and would give a pretty accurate count of the hand for the end position. LHO also had the AKJ of diamonds.

This was all unncessary, though, as RHO had the singleton HT! LHO also had discarded two hearts, so we ended up making 10 tricks in 3NT.
 
We should have won IMPS on this board for bidding and making an overtrick 3NT, instead of doubling them non-vul in 3D (which is down 2/3), right? (or at least broken even?).

Unfortunately we lost IMPS. Teammates got to 4DX and went down 4. Ouch.

Friday, October 23, 2015

Quicksort in log space

This is a classic.

Can you implement simple quicksort: with the first element as the pivot, to in-place sort an array of size $n$, so that the implementation uses $O(\log n)$ space in the worst case?  If you use recursion, the stack depth is also counted.

[Assume WORD RAM model].

[Solution]

Wednesday, October 21, 2015

Inequality from UW challenge of the week

The UW math department (students) used to have a challenge of the week where they would post high school/undergraduate level math problems.  The winner would be selected randomly from the list of correct solvers, and given a gift certificate to Baskin Robbins!

Here is one problem:

Suppose $x_1, x_2, \dots, x_n$ are real numbers such that

$$ x_1 + x_2 + \dots + x_n = 0$$

and

$$ x_1^2 + x_2^2 + \dots + x_n^2 = 1$$

Show that there are some $i,j$ such that $$x_i x_j \le -\frac{1}{n}$$


[Solution]

Tuesday, October 13, 2015

A hand from the Chennai Bermuda Bowl

No, I didn't play in the Bermuda Bowl. This came up while using BBO's Vugraph table feature, which allows you to select hands from previously played tournaments.

You hold QJx, Qx, AKQxxxx, x. RHO opens 1S, you overcall 2D, 4S by LHO, 4NT (blackwood) by partner and you end up in 6D.

LHO leads a spade and you see

IMPS
N/S 
 North
♠ -
♥ K98xx
♦ JTx
♣ AJxxx

     


 South
♠ QJx
♥ Qx
♦ AKQxxxx
♣ x

W N E S
1S2D
4S4NTP5S
P6DPP
P

The contract is a good one and you are lucky that partner took a rosy view.

How will you play?


This hand has elements of a Morton's fork. 

Suppose you ruff the first spade and immediately play a low heart towards the Queen. RHO, who likely has the Heart Ace, now has to decide whether to go up with the A and play a trump (to avoid a spade ruff), or to let your Q win.

If he lets your Q win, then you can ruff a spade, CA, C ruff in hand, spade ruff, club ruff and draw trumps. This only loses if RHO has 5+ clubs, and even then you can choose to ruff the third club high in hand and survive if trumps are 2-1.


If he goes up with the HA and plays a trump, you can win in hand, cash the HQ, play a trump to dummy, ruff a heart back to hand, draw any remaining trumps (if any), and then CA to dummy to cash the HK and low heart to take care of your spade losers. This just requires a 4-2 heart break.

Sunday, October 11, 2015

All starting points [Solution]

The problem was:

A circular road, with $n$ petrol stations, which just enough petrol to complete one full circle along the road. You have a car with an empty tank (but infinite capacity), and can start at any petrol station an drive along the road, filling petrol along the way.

You need to find all the stations that will allow you to complete a full circle without running out of petrol.

The algorithm needs to run in $O(n)$ time.

Solution


Note that we allow the car to travel either clockwise or anti-clockwise. We will provide a solution for the clockwise case, the other is similar. Also note that if the car chooses to go in one direction first, it has to continue along that direction.

We were given the input as $p_1, p_2, \dots, p_n$ and $d_1, d_2, \dots, d_n$

where $p_i$ was the amount of petrol in station $i$, and $d_i$ was distance between station $i$ and $i+1$ (written in clockwise consecutive order).

Let $e_i = p_i - d_i$, the amount of petrol left in the car, if an empty car starts at station $i$ and goes to station $i+1$. Note that $e_i$ could be negative.

Suppose we start at station $k$. Then the amounts of petrol that will be in the car at each station will be
$$e_{k}, e_k + e_{k+1}, \dots, e_k + \dots + e_n, e_k + \dots + e_n + e_1, \dots, e_k + \dots + e_n + e_1 + \dots + e_{k-1}$$

We need each of those to be non-negative.

Let $S_k = e_1 + e_2 + \dots + e_k$. We are given that $S_n = 0$ and the above intermediate amounts are

$$S_{k+1} - S_k, S_{k+2} - S_k, \dots, S_n - S_k, S_n - S_k + S_1, \dots S_n - S_k + S_{k-1}$$

Thus we need that for every $j$, since $S_n = 0$ that

$$ S_j \ge S_k$$

Thus we need to pick all the $k$ such that $S_k$ is the smallest.

Repeat in the other direction and we are done.
 

The $S_n \gt 0$ case is more interesting, and can still be solved in $O(n)$ time.

Now the conditions become

1) $ S_j \ge S_k$, for $j \gt k$

and

2) $ S_j + S_n \ge S_k$, for $j \le k$.


The candidates satisfying condition 1) can be computed by traversing the $S$ array from right to left, keeping track of the minimum seen so far.

The candidates satisfying condition 2) can be computed by traversing the array from left to right and keeping track of the smallest possible value of $Sj + S_n$.

Thursday, October 8, 2015

Four Number Game II [Solution]

This was the puzzle:

You start with $n$ integers $a_1, a_2, \dots, a_n$ and in one step you perform the following transformation

$$(a_1, a_2, \dots , a_n) \to (|a_1-a_2|, |a_2 - a_3|, \dots, |a_{n-1} - a_n|, |a_n - a_1|)$$

($|x| = $ absolute value of $x$)

You keep performing this operation till all the numbers become zero.

Find all $n \gt 1$ (with proof), such that no matter which integers you start with, the numbers eventually become zero.

Solution


 The answer is the game terminates for every starting tuple of integers if and only if $n$ is a power of $2$.

The proof is based on the following observations (note, you might have to fill in a few details):

Lemma 1)

It is enough to consider the game modulo $2$, i.e, we play the game as

$$(a_1, a_2, \dots , a_n)  \to $$
$$ (|a_1-a_2| \mod 2, |a_2 - a_3| \mod 2, \dots, |a_{n-1} - a_n| \mod 2, |a_n - a_1| \mod 2)$$

which is equivalent to the game, working in the field $\mathbb{F}_2$ (where each $a_i$ is $0$ or $1$ and $1+1 = 0$) as

$$(a_1, a_2, \dots , a_n) \to (a_1 + a_2, a_2 + a_3, \dots, a_{n-1} + a_n, a_n  + a_1)$$


Lemma 2)

Looking at the tuples as vectors over $\mathbb{F}_2$, if the game terminates for $u$ and $v$, then the game terminates for $u+v$.

Now the game is basically multiply a vector $v$ by a fixed matrix $A$, and the game terminates if $A^k v = 0$ for some $k$.

Lemma 3)

If the game terminates for $e = (1,0, \dots, 0)$, then the game terminates for all vectors in $\{0,1\}^n$. This is because we can cyclic shift $e$ to get that the game terminates for $(0, 1, \dots, 0)$ etc, and add as appropriate (by Lemma 2).

Lemma 4)

 If the game terminates for $e = (1, 0, \dots, 0)$, it does so in no more than $n$ steps!

This we can see by considering the starting state $v$, and the subsequent states $Av, A^2v, \dots, A^nv$.

Now suppose we have that $A^mv \ne 0$ for all $m \lt K$, and $A^K v = 0$.

The claim is that $v, Av, A^2v, \dots, A^{K-1}v$ are all linearly independent vectors.

If they were linearly dependent, then we have that

$$A^{s_1} v + A^{s_2}v + \dots = 0$$

with $s_1 \lt s_2 \dots \lt K$

Now just multiply the above with $A^{K-1-s_1}$ to get that $A^{K-1}v = 0$.

Since the $K$ vectors are linearly independent, we have that $K \le n$.

Main proposition)

The game played on $(1, 0, \dots, 0)$ gives us the rows of the Pascal's triangle on each step, and we are looking for all numbers to become even within $n$ steps.

We can now use Lucas' theorem to show that the only $n$ for which termination occurs is powers of $2$.

More reading: https://en.wikipedia.org/wiki/Ducci_sequence

Monday, October 5, 2015

Only hope

This is a hand from a casual game in Google Seattle (so assume IMPS and some vulnerability).

You hold Q765, AT, KJ43, 543.

RHO is the dealer and opens 1C, you pass, LHO passes, partner doubles, pass by RHO, you bid 2S and partner jumps to 4S.

LHO leads the club 8 (they play MUD, if it matters), and this is what you see:

IMPS
None 
 North
♠ 432
♥ Q43
♦ AQ76
♣ AKQ

     


 South
♠ Q765
♥ AT
♦ KJ43
♣ 543

W N E S
1CP
PXP2S
P4SPP
P


You ought to have been in 3NT by partner, which is cold, and you will reach that if partner just bid normally. But, you are in 4S now.

You win in dummy and play a spade. RHO wins the K of spades, cashes the Ace of spades and leads back a club. You win, LHO following with a low card. When you play a spade from dummy, RHO throws a club.

How will you play?




You have three trump losers. The only hope of making this contract is that LHO holds the heart Jack, and you endplay LHO to lead a heart. You just need to guess LHO's minor suit distribution correctly. If LHO has 3 clubs and 2 diamonds, you need to cash 2 diamonds and a club, and then endplay LHO. If you guess incorrectly, LHO can ruff early and have a card to exit with.

Now RHO has AK of spades, K of hearts and J of clubs, with no more than 4 hearts and 5 clubs. So RHO has at least 2 diamonds.

If RHO was balanced with 11 points, RHO might not have opened. So give RHO some distribution, and hence 5 clubs (also consistent with the discards). RHO could have beaten the contract legitimately by giving LHO a club ruff while he still had exit cards, but that is a difficult defense to find.

Thus we play LHO to hold two clubs. So the plan is: win the SQ, cash three rounds of diamonds ensuring a hand entry, then cash a club and then the last diamond to hand, planning to throw LHO in with a spade. LHO can ruff in (or not) anytime time, but then has to lead a heart ensuring two tricks there.


Tuesday, September 29, 2015

All starting points

This is an extension of a classic puzzle.

You have a circular road, with $n$ petrol bunks (or gas stations as called in America) located somewhere along the road. You are given the length of each segment of the road, which is between two petrol bunks. You are also given the amounts of petrol left in each bunk. You are also told that the total amount of petrol is just enough to complete exactly one lap of the circular road, using a car that starts with an empty tank. The car has infinite capacity and you fill whatever you can when you reach a petrol bunk.

Now given a car with an empty tank, you need to find out in $O(n)$ time, all the possible starting points which will allow you to complete the lap. [The classic puzzle was to prove that there is a such a starting point].

The petrol bunks are numbered $1$ to $n$, and you are given an array $p[1, \dots, n]$ of the amounts of petrol, and a distance array $d[1, \dots, n]$ of the distances between the petrol bunks ($d[i] = $ distance between $p[i]$ and $p[i+1]$). The output will be a list of numbers between $1$ and $n$, denoting the petrol bunks you can start at.

Assume that one unit of petrol covers exactly one unit of distance.

[Solution]

Thursday, September 24, 2015

Four Numbers Game II

In an earlier post a question was left open. I will repeat the question here.

You start with $n$ integers $a_1, a_2, \dots, a_n$ and in one step you perform the following transformation

$$(a_1, a_2, \dots , a_n) \to (|a_1-a_2|, |a_2 - a_3|, \dots, |a_{n-1} - a_n|, |a_n - a_1|)$$

($|x| = $ absolute value of $x$)

You keep performing this operation till all the numbers become zero.

Find all $n \gt 1$ (with proof), such that no matter which integers you start with, the numbers eventually become zero.

Friday, September 11, 2015

Opening Lead problem

This is a hand from a recent regional in Lynwood, WA (near Seattle).

Playing a knockout game,  you hold JTx, Kxxx, xx, Jxxx, white vs red.

LHO is dealer and opens 1S. Partner overcalls 2H, RHO bids 3D. You bid 3H, LHO bids 4D, partner bids 4H, and opponents buy the contract in 5D (the auction is as I remember, it might have been different at the table).

What would you lead?



You probably led a heart? If so, hope you had led the HK!

These were the four hands (you are west)

IMPS
N/S 
 North
♠ Axxxxx
♥ T
♦ Txxx
♣ AQ
 West
♠ JTx
♥ Kxxx
♦ xx
♣ Jxxx

     


 East
♠ KQ
♥ AQJxx
♦ xx
♣ KTxx
 South
♠ xx
♥ xxx
♦ AKQJx
♣ xxx

W N E S
1S2H3D
3H4D4H5D
PPP

If you lead a low heart, declarer can make the contract by setting up the spades. Partner cannot attack clubs.

If you lead the HK, you can hold the lead and switch to a club, establishing your club trick before declarer can set up spades, and the contract goes down one.

A club lead would have worked too.

Leading the HK is "standard" with that hand, and I believe most advanced players would find it.

Thursday, September 10, 2015

Span sums [Solution]

The problem was here.

In short, compute the total of the spans for each sub-array of a given array, the span of an array being the difference between the maximum and minimum element of the array.

Solution

Note that it is enough to figure out the sum the maximum elements of each array [and minimum, and then take the difference].

Suppose we want to find the max sum of sub-arrays of an array $A[1,\dots,n]$, and the maximum element of $A$ appears at $A[M]$. Assume the elements are distinct for now, but does not really matter.

Now $A[M]$ is the maximum of any subarray $A[i,\dots,j]$ where $i \le M \le j$ and thus contributes $A[M]\times M \times (n-M+1)$ to the total we seek.

Now we recursively compute the totals for $A[1,\dots,M-1]$ and $A[M+1,\dots,n]$ and add all those up.

This can be done in $O(n)$ time, if we compute the cartesian tree corresponding to the array (which can be done in $O(n)$ time).

The cartesian tree is basically a max-heap whose inorder traversal gives back the array in the order $A[1], A[2], \dots$. The whole tree corresponds to $A[1, \dots, n]$, while the left subtree of the root corresponds to $A[1, \dots, M-1]$ and the right sub-tree corresponds to $A[M+1, \dots, n]$.

In order to get past the distinctness assumption, we can work with $B[i] = (A[i], i)$ instead.

[See: http://ruffnsluff.blogspot.com/2015/05/max-area-in-histogram-solution.html for an explanation of Cartesian trees. There is a diagram too!]


Tuesday, September 1, 2015

Prime binomial sum [Solution]

The problem was to show that

$$ \sum_{k=1}^{\lfloor 2p/3 \rfloor} \binom{p}{k}$$

is divisible by $p^2$ for a prime $p \ge 5$.

Solution


Now working in the field $F_p$  (where division makes sense) we have that

$$ \frac{\binom{p}{k}}{p} = \frac{(p-1)!}{k! (p-k)!}  = \frac{(p-1)(p-2)\dots(p-k+1)}{k!}$$

$$ = \frac{(-1)(-2)\dots(-(k-1))}{k!} = \frac{(-1)^{k-1}}{k}$$


Let $ T = {\lfloor 2p/3 \rfloor}, U = \lfloor \frac{T}{2} \rfloor$

Thus the sum we need to show divisible by $p$ (note that we divided by $p$ already) is

$$\sum_{k=1}^{T} \frac{(-1)^{k-1}}{k}$$


$$ =  \sum_{k=1}^{T} \frac{1}{k} - 2\sum_{k=1}^{U} \frac{1}{2k}$$

$$ = \sum_{k=U+1}^{T} \frac{1}{k}$$

Now $T + U + 1 = p$ so this sum becomes

$$ \frac{1}{T} + \frac{1}{U+1} + \frac{1}{T-1} + \frac{1}{U+2} + \dots $$

(by coming terms from the ends)

$$ = \frac{p}{T(U+1)} + \frac{p}{(T-1)(U+2)} + \dots $$

which is divisible by $p$.

Friday, August 21, 2015

5D making 5

This hand reminds me of Belladonna's famous 6D hand (see this: http://ruffnsluff.blogspot.com/2015/01/6d-making-6-hand-played-by-belladonna.html).

Playing a casual game [lunch bridge in Google Kirkland], you are South, and end up in 5D with west preempting in spades (showing exactly 6).

The bidding: partner (North) opens 1C, East passes, you bid 1D, 2S by West, and you end up in 5D (3NT is better).

West leads the HJ.

This is what you see.

IMPS
None 
 North
♠ A32
♥ Q32
♦ K42
♣ AT82

    


 South
♠ 4
♥ K654
♦ AQJ53
♣ K93

W N E S
1CP1D
2S....

You play low from dummy and RHO plays low too, and you win the K in hand.

How will you play? [For simiplicity, assume 3-2 diamonds if you want].


You have 9 tricks (3NT would have been great!), and need two more. So a simple squeeze or a simple endplay will not work (you get back one trick). In fact, you might need to combine both!

Assuming trumps are 3-2, there are a couple of possible lines.

1) Play RHO to have QJx of clubs.

2) Play RHO to have a single club honour and 4+ clubs.

If you go for line 1), you can eliminate spades while drawing trumps, and play AK clubs and a club, setting up your 4th club. RHO is in, and now has to give you the 11 trick by playing a heart.

If you go for line 2), you can eliminate spades while drawing trumps, but have to watch for RHO's discard. If RHO discards a heart (presumably from 3-4-2-4) you can now play a heart to the Q. If RHO now returns a club honour you can setup your clubs. If RHO returns a low club, you can win in dummy and lead another heart, setting up the heart in had, and endplaying RHO again.

If RHO discards a club, you can try to endplay RHO in clubs (AK and club), forcing RHO to give you a heart trick with the Q, and an entry to dummy for the good clubs.

Line 2 seems better.

You squeeze RHO, then endplay RHO while setting up a suit and generate two tricks in the process, similar to the hand played by Belladonna.

Interestingly, if RHO had 5 hearts, the winning defense is to win the HA at trick one, and give partner a ruff!

Tuesday, August 18, 2015

Span sums

A span of an integer array is the difference of the maximum and the minimum elements.

For example, span of $[3,4,8,1,-1]$ is $8 - (-1) = 9$. The span of a single element array is $0$.

Given an array $A$ of $n$ integers, can you find the sum of spans of all the subarrays of $A$? (subarray is a contiguous subset). For example $[4,8,1]$ is a sub-array of $[3,4,8,1,-1]$ and $[4,8,1, 5]$ etc.

Try for an algorithm which runs in $O(n)$ time.

[Solution]

Monday, August 17, 2015

Prime binomial sum

I believe this is a problem from an International Mathematical Olympiad. [Don't know the year].

$p \ge 5$ is a prime number.

Show that

$$ \sum_{k=1}^{\lfloor 2p/3 \rfloor} \binom{p}{k}$$ is divisible by $p^2$.


[Solution]

Friday, August 14, 2015

Spots and Entries

This is a hand from a casual game in Google Seattle and an instructive hand about using spots and unblocking for entry management.

Assume IMPS.

You are South and hold AJ92, AQ87, K6, KQT.

Your RHO opens 1S, you double, LHO passes, and you eventually end up in 3NT.

LHO leads a low club, and you see:

IMPS
None 
 North
♠ T873
♥ 2
♦ A5432
♣ 543

     


 South
♠ AJ92
♥ AQ87
♦ K6
♣ KQT

RHO wins the CA and returns a high club spot.

How will you play? [Please think about it before reading on].






Assuming RHO has the HK (which you need to, and is quite likely), you can guarantee the contract, thanks to the spade spots!

With ample entries to dummy, you would have 3 spade tricks, 2 hearts, 2 diamonds and 2 club tricks.

The spade spots and the DA can help you achieve that.

Consider what happens when you win the second club trick and lead the spade jack from hand.

Suppose RHO wins the SJ and returns a club. Now you play a diamond to the A, and play the ST. If RHO covers the ST, you win, and you have a spade entry to dummy to take the heart finesse, and 3 spade tricks. If RHO ducks the ST, you drop the 9 from hand, and then play the S8. If RHO does not cover, you take the heart finesse. If RHO covers, you win and have a spade entry.

If RHO ducks the SJ, you play the S9 to the ST. If RHO ducks this, you have enough entries. If RHO wins the ST, you can win the club return, play a diamond to the A, and play the S8, and be in a situation similar to the previous paragraph.

Wednesday, August 12, 2015

Sort binary tree array [Solution]

The problem was to sort an almost complete binary search tree, which is represented as an array: the children of $a[i]$ are $a[2i]$ and $a[2i+1]$.

The catch was to sort in $O(n)$ time and using $O(1)$ space.

[Detailed problem statement is here]

Solution


The solution depends on the following

1) If $a[1], a[2], \dots, a[2^k-1]$ is already sorted, then we can sort $a[1], a[2], \dots, a[2^{k+1}-1]$ by interleaving $$\{a[1], a[2], \dots, a[2^k-1]\}\quad \{a[2^k], a[2^k+1], \dots, a[2^{k+1}-1]\}$$ as

$$ a[2^k], a[1], a[2^k+1], a[2], \dots, a[2^{k+1} -2], a[2^k-1], a[2^{k+1}-1]$$

Now this interleaving can be done on linear time and constant space, using the solution in the blog post here: http://ruffnsluff.blogspot.com/2015/01/solution-to-rearrange-array-algorithm.html


So starting with $k=1$ and so on, we can do this in time  $n + n/2 + n/4 + \dots$ = $O(n)$ and $O(1)$ space.


[Sorry for the terse solution, I suggest you try it out with a few examples].

Monday, August 3, 2015

Find the unique root [Solution]

The problem was:

It can be shown that the below equation has a unique root in the interval $(0,2)$.

Can you find it?

$$ \sqrt{2 + \sqrt{2 - \sqrt{2 + x}}} = x $$

Solution


This can be solved neatly using trigonometry!

Set $x = 2\cos \theta$ for some $\theta \in \left[0, \dfrac{\pi}{2}\right]$

Now $$\sqrt{2+x} = \sqrt{2 + 2\cos \theta} = 2 \cos \frac{\theta}{2}$$ using the double angle formula $1 + \cos 2y = 2 \cos^2 y$.

Then use $1 - \cos 2y = 2 \sin^2 y$ and $ \cos y = \sin (\pi/2 - y)$, and you can find out what $\theta$ is.

Thursday, July 30, 2015

Interesting end position [Bothell sectional swiss teams hand]

This is a hand from a recent swiss teams event in Bothell, near Seattle.

You are South and dealer, holding 85, AK954, KQJ82, A

You open 1H, LHO overcalls 2C, partner bids 2H, pass, 3D from you, pass, 3H by partner and you buy the contract in 4H.

LHO leads the CK and you see:

IMPS
Both 
 North
♠ AJ942
♥ 732
♦ 96
♣ 854

   


 South
♠ 85
♥ AK954
♦ KQJ82
♣ A

W N E S
1H
2C2HP3D
P3HP4H
PPP

You win the CA, and play the DK. LHO wins the DA and plays back a club, which you ruff (RHO following to both clubs).

Now when you play HAK, LHO follows with the 6 and Q, and RHO with the 8 and T. When you play the DQ, LHO shows out, throwing a club.

How will you play? [Please think about it before reading on]




At the table, I decided to play RHO to hold the third trump, and if that is the case, you can guarantee the contract!

[Note that there is 50% chance that RHO holds the third trump, using a vacant spaces argument. If you consider some restricted choice argument about LHO throwing HJ from QJ6, the chances are even more. LHO might have even ruffed your DQ...]

After getting the news of the 5-1 diamond split, and assuming RHO has the third trump, you can make it as follows:

Ruff a low diamond in dummy, and play a club from dummy.

If RHO started with 2 clubs, (3=3=5=2 hand), then, on the third club from dummy RHO is caught in a strange squeeze. If he throws a diamond, your diamonds are good. If he ruffs with the HJ, you can throw a loser. Thus he is forced to throw a spade, and come down to 2 spades.

Once RHO throws a spade, you ruff the club in hand (and are now left with 2 spades, a trump and 2 diamonds), and play spade to the A, and a spade back.

If RHO wins the second spade, he can cash his trump, but has to lead into your diamond tenace (thanks to the D8!).

If LHO wins the second spade, then he can only return a spade or a club, in which case you make your last trump en-passant, and can cash the DJ for the tenth trick.

RHO following to the third club is similar.

At the table RHO did in fact have a 3=3=5=2 hand, and was subject to the squeeze, and the defense chose to let RHO win the second spade to lead into the diamond tenace.

Did we win IMPS on this hand? Unfortunately no, as our teammate at the other table led the DA, resolving any issues for declarer, resulting in a push.

If you want to try playing around with the full hand, you can use this handviewer link.

Wednesday, July 29, 2015

Sort an almost complete binary search tree array.

Almost complete binary trees can be represented compactly using arrays, where the children of $a[i]$ are $a[2i]$ and $a[2i+1]$, with the root being $a[1]$ (assume index of the array starts at 1 for this problem).

Given an almost complete binary search represented in such a manner: i.e. given the array $A$ representing the tree, can you give an $O(n)$ time and $O(1)$ space algorithm (WORD RAM model) which will sort the array?


For example if the tree is [image swiped from someone's webpage in cmu]




the corresponding array would be

$$ [10, 6, 18, 4, 8, 15, 21] $$

and your algorithm needs to sort it so that it becomes

$$ [4, 6, 8, 10, 15, 18, 21] $$
 [I have labelled this hard, because the solution I have uses a result which is hard. Hint: You can find that result on this blog]

[Solution]

Tuesday, July 28, 2015

Find the unique root

It can be shown that the below equation has a unique root in the interval $(0,2)$.

Can you find it?

$$ \sqrt{2 + \sqrt{2 - \sqrt{2 + x}}} = x $$

[Solution]

Wednesday, July 22, 2015

Matchpoint greed?

This is a hand from yesterday's Matchpoint game at Mercercrest bridge club, in Mercer Island near Seattle.

You are South and end up in 4S, after showing 6 hearts and 5 spades, and North showing a diamond suit.

[In the actual hand, East was declarer, made South here for convenience]

West leads a trump. You see:

MPS
Both 
 North
♠ KT9
♥ -
♦ KT97642
♣ KT5

     


 South
♠ QJ543
♥ A87543
♦ A5
♣ -

W N E S
1H
P1NTP2H
P3DP3S
P3NP4S
PPP

[Bidding given is as it happened at the table]

East wins the SA (low from dummy), and returns a trump (win in dummy with the T), West following.

Now what?

At the table, South played a diamond to the A (both opponents following with low cards), and a diamond toward the K, with West playing the DJ.

If this was IMPS, you have a clear play to duck this trick!

You are short of entries to dummy. If diamonds break 3-1 (singleton with East), and you play the K, East might be able to ruff and dummy's diamonds will be dead. There will be no way to establish (the Q is still out) and cash the diamonds.

If you duck, the diamonds are already setup, with the SK as an entry.

Coming back to matchpoints.

If you duck, you guarantee 11 tricks.

If you go up with the K and diamonds are 2-2, you make 12, risking going down if diamonds are 3-1.

At the table, South got greedy and went up with the K. Unfortunately for her, this got ruffed, and she ended up down 2, when she threw a heart on the club return.

Looking at the traveller, she would have made a near top if she made 11 tricks. Getting greedy, she got a near bottom.

I think she got greedy, but perhaps you disagree. How would you have played?

Sunday, July 12, 2015

Sorting with reversals II [Solution]

The problem was:

You have an size $n$ array of zeroes, ones and twos. The only write operation is to reverse a sub-array (paying cost equal to the length of the the sub-array). Can we sort the array in $O(n \log n)$ cost?

Solution

One solution is to use divide and conquer.

Suppose you divided the array into two approximately equal halves, and sorted each sub-array separately.

Then you will see an array like


$$0 \dots 0 1 \dots 12 \dots 2\vert 0 \dots 0 1 \dots 1 2 \dots 2$$

Now, we can sort a chunk of 2s and 0s by doing a cyclic shift of the chunk $2 \dots 2 0 \dots 0$, so that it looks like $ 0 \dots 0 2 \dots 2$.

We can do a cyclic shift of an array using only three reversals. Say you want to cyclic shift $a_1, \dots a_m$ to look like $a_k, a_{k+1}, \dots, a_m, a_1, a_2, \dots a_{k-1}$. This we can achieve by first reversing $a_1, \dots a_{k-1}$ and $a_k \dots a_m$, so the array now looks like $a_{k-1}, \dots a_1, a_m, \dots a_{k+1}, a_k$ and then reversing the whole array.

Each reverse costs $O(n)$, and with a constant number of these, give the two sorted halves, we can sort the whole array.

Thus the cost satisfies the recurrence

$$ C(n) = 2 C(n/2) + O(n)$$

which gives us $C(n) = O(n \log n)$.

Friday, July 10, 2015

Consecutive product sum [Solution]

The task was to find (without pen and paper)

$$\sum_{k=r}^{n} k(k-1)\dots(k-r)$$

Solution


Let $S_k = k(k-1) \dots (k-r)$.

One way to solve this is to notice that

$$(k+1)k(k-1)\dots(k-r) - k(k-1)(k-2)\dots(k-r)(k-r+1)$$

$$= (k+1-(k-r+1))k(k-1)\dots(k-r) = r k(k-1)\dots(k-r)$$

i.e

$$P_k - P_{k-1} = rS_k$$

where $P_k = (k+1)k(k-1) \dots (k-r)$

Thus we get a sum where most of the terms cancel each other out (called a telescopic sum) and the answer is simply $P_n - P_{r-1}$ which is

$$\frac{(n+1)n(n-1)\dots(n-r)}{r}$$

There are other solutions, like writing in terms of binomial coefficients etc, not sure we can do those without pen and paper though.

Monday, July 6, 2015

Sorting with reversals II

In a previous post, we were asked to sort an array (of size $n$) consisting only of the elements 0,1 and 2. The catch being: the only write operation on the array that was allowed was to reverse a sub-array $A[i, i+1, \dots, j]$.

The task was to use $O(n)$ reversals.

This problem is similar. We still have an array of zeroes, ones and twos, and we can only write by doing reversals.

The difference is that the reversal has a cost associated with it.

Reversing the sub-array $A[i, i+1, \dots, j]$ has cost $j-i+1$ associated with it (similar to what you would normally pay when doing an actual reverse).

Can you now sort the array with $O(n \log n)$ cost?

[Solution]

Sunday, July 5, 2015

Consecutive product sum

Can you solve this without pen and paper?

Suppose $r \gt 0$ is a fixed positive integer.

Can you give a formula (in terms of $n$ and $r$) for


$$ \sum_{k=r}^{n} \left( \prod_{j=0}^{r} (k-j) \right)$$

i.e.

$$\sum_{k=r}^{n} k(k-1)(k-2)\dots(k-r)$$


[Solution]

Thursday, July 2, 2015

All is not lost

This hand came up while playing a local game at Mercercrest bridge club in Mercer Island, near Seattle (one heart spot modified for the narrative). The club participates in the common game, night version.

You are West holding AQ5, QJ, KT654, J83. E/W vul with E dealer.

After two passes, you open 1D (likely 4+), double by LHO, 1H by partner, 2S by RHO which gets passed out.

You lead the HQ and you see:

MPS
E/W 
 North
♠ K832
♥ A843
♦ 73
♣ Q62
 West
♠ AQ5
♥ QJ
♦ KT654
♣ J83

   



W N E S
PP
1DX1H2S
PPP


Not everyone will double with that hand.

Declarer goes up with the HA (partner encouraging) and plays a club to the A, partner showing an odd number.

Now declarer plays the S9. You choose to duck, as dummy and partner both follow with a low card.

Now declarer plays another spade, on which you go up with the SA, partner following.

To beat 2S, you need to be able to get 2 heart tricks, 2 diamonds and 2 spades. Thus you assume partner is 2-4-4-3 with the DA and DK and a fourth round of hearts can promote your SQ.

You play the HJ, it wins and you now quickly play a low diamond, and partner wins the DA. Partner now plays the HK, declarer following with the T.

At this point you realize your mistake. Instead of a low diamond, you should have played the DK first. Then a diamond to the DA, HK, followed by another heart by partner, and you get your SQ.
[A defensive version of the cross-ruff principle for declarer: cash you side suit tricks before you start your crossruff, otherwise the opponents(s) will throw the cards in the side suits and you won' get your winners there.]

As you played it, declarer (with a 4-3-2-4 hand) can throw his losing diamond on the fourth heart.

But all is not lost!

Partner seems to have started with HK9xx in which case you have a chance!

You are left with two clubs (declarer had played one round earlier). You throw one of them on the HK. Now when partner plays the H9 (the top heart at that moment), if declarer throws his last diamond, you can throw your last club! Partner can now give you a club ruff, for down one.

Even if you make a mistake, it might not be the end. There still might be opportunities lurking. The same is true not just for a single hand, but for the whole match. Don't let one mistake mess up the other hands for you, which will happen if you dwell upon your mistakes. You should definitely look at your mistakes (how else will you improve?), but only after the match. It is easier said than done, though.

[Beating 2S gives you just an average+ (while playing and making 3D is a near top), so, I guess the real moral of the story is to bid 3 over 2 in matchpoints, even with only an eight card fit...]

Wednesday, July 1, 2015

Sorting with reversals [Solution]

The problem was to sort an array consisting of only 0,1,2 only using $O(n)$ reversals of subarrays.

When I posted this problem, I had one solution in mind (which I will not reveal just now, but try to reuse for the next problem), without realizing that swapping $A[i]$ and $A[j]$ can be done using two reversals: reverse $A[i, \dots, j]$ and then reverse $A[i+1, \dots, j-1]$!

So any sorting algorithm which uses $O(n)$ swaps should do.

For example, using the Dutch National Flag (DNF) algorithm, we can achieve sorting in $O(n)$ reversals.

Collins made a nice observation that if we use the DNF algorithm, we don't even need to do the second reverse when trying to swap $A[i], A[j]$. See the comments on the question.

Sunday, June 28, 2015

How many non-decreasing functions [Solutions]

The problem was to find the number of ordered pairs $x = (x_1, x_2, \dots, x_n)$ such that $x_i \le x_{i+1}$ and $1 \le x_i \le m$ for all $i$, $x_i$ being a natural number.

Solution

We will present two solutions.

Solution 1)

The first solution uses what is called the Stars and Bars approach.

For each $k \in \{1, 2, \dots, m\}$ you look at exactly how many $x_i = k$. Call this number $y_k$ (note, it could be $0$).

We must have that $y_1 + y_2 + \dots + y_m = n$, with $0 \le y_i \le n$.

Now given a $y = (y_1, y_2, \dots, y_m)$ we can easily map this back to the $x = (x_1, x_2, \dots, x_n)$ from which it was created.

Thus it is enough to count the number of solutions to $y_1 + y_2 + \dots + y_m = n$, with $0 \le y_i \le n$.

The way to look at this is to consider $n$ stars, and $m-1$ vertical bars. Finding a solution to the above equation is equivalent to placing the $m-1$ bars among the $n$ stars. The number of stars to the left of the leftmost bar is $y_1$, the one next to it is $y_2$ and so on.

The number of ways to do this is to select the position of the stars among a total $n + m - 1$ spots: $$ \binom{n+m-1}{n}$$

Solution 2)

The second solution I find particularly elegant.

Suppose instead of $x_i \le x_{i+1}$, we had the condition $x_i \le x_{i+1}$ (i.e. strictly increasing).

Then it is easy to count: just select $n$ among $m$ = $\binom{m}{n}$ (and sort to get the increasing order).

We can reduce our problem to the strictly increasing case.

Set $z_i = x_i + i - 1$.

Now we have that $z_i \lt z_{i+1}$ (strictly increasing) and that $ 1 \le z_i \le m + n - 1$.

Thus the answer is $$\binom{m+n-1}{n}$$

Saturday, June 27, 2015

Sorting with reversals

You are given an array $A$ of $n$ elements, each element being either $0$ or $1$ or $2$.

You want to sort the array.

The catch is, the only write operation you can do on the array is pick two any two indices $i \le j$, and reverse the contiguous portion of the array from $A[i]$ to $A[j]$, i.e. after the operation, $A[i]$ and $A[j]$ are swapped, $A[i+1]$ and $A[j-1]$ are swapped, $\dots ,A[i+k]$ and $A[j-k]$ are swapped (where $k \approx (i+j)/2$).

Let's say we call this operation the splice-reverse.

Can you sort the array using $O(n)$ splice-reverses?

[Solution. Also see comments below]

Thursday, June 25, 2015

How many non-decreasing functions?

How many non-decreasing functions exist which map $\{1, 2, \dots, n\} \to \{1, 2, \dots, m\}$?

i.e

How many ordered pairs $(x_1, x_2, \dots, x_n)$ exist such that

$x_i \le x_{i+1}$ and $ 1 \le x_i \le m$ for all $i$?

[Solution]

Sunday, June 21, 2015

Bless partner, curse partner.

You are South and hold QJ9642, 2, 5, AQ872, with E/W vul.

Your LHO is the dealer and opens 1H. Partner doubles and RHO bids 4H. You bid 4S, wondering if you missed a slam.

LHO passes, and bless partner, who bids 6S.

LHO lead the DA and you see

IMPS
E/W 
 The Dummy
♠ AKT73
♥ AQ
♦ KJT
♣ J94

     


 You
♠ QJ9642
♥ 2
♦ 5
♣ AQ872

W N E S
1HX4H4S
P6SPP
P

Curse partner. Overbid again.

While you are cursing partner, LHO goes into a tank, and emerges with a low club! Now you have a chance. Bless partner?

You play the 9, covered by the T, which you win with the Q.

Now LHO likely has the HK, DQ and the CK for his opening bid. In that case you have him, but have to time the hand correctly.

You should play all the trumps, throwing a club from dummy, then play a heart to the Q, and cash the HA and DK coming down to the DJ and CJ in the dummy and CA8 in hand.

West is squeezed in the minors.


Thursday, June 18, 2015

Sum involving golden ratio [Solution]

The problem was to find

$$S_n = \sum_{k=1}^{n} [k \varphi]$$

where $\varphi$ is the golden ratio and $[x]$ is the integer part of $x$.

The challenge was to do it using polynomial in $\log n$ time.

Solution

If you look at the numbers of the form $a_k = [k \varphi]$ and *not* of the form $[k \varphi]$, you will notice a pattern.

The pattern is as follows:

If $a_k = [k \varphi]$ and $b_k = a_k + k$, then we have that $$\{a_1, a_2, \dots\} \cup \{b_1, b_2, \dots\} = \mathbb{N}$$

i.e, the numbers not of the form $[k \varphi]$, are precisely of the form $[k \varphi] + k$.

This observation can be proved using Beatty's theorem (and is not that difficult to prove).

Now, if you consider the numbers $\{1, 2, \dots, a_n\}$ then these can be split into two disjoint sets $\{a_1, a_2, \dots, a_n\}$ and $\{b_1, b_2, \dots, b_m\}$ for some $m$.

Thus we have that

$$1 + 2 + \dots + a_n = S_n + \sum_{k=1}^{m} b_m = S_n + S_m + m(m+1)/2$$

Thus

$$S_n = n(n+1)/2 - m(m+1)/2 - S_m$$

which is a recursive formula for $S_n$. It can be shown that $m = \theta(n)$, and thus this recursive formula gives us a polynomial in $\log n$ time algorithm to compute $S_n$.

All we need to do is compute $m$. I will leave that to you.

Monday, June 15, 2015

Limit everywhere function [Solution]

The problem was to find a function $f$ whose limit $g$ exists everywhere (i.e. $\lim_{t\to x} f(t) = g(x)$) and $f(x) = 2g(x) - \sin x$.

The key is to realize that $g$ must continuous!

(In fact one can show that $f$ is continuous almost everywhere, but that does not help this problem immediately).

If $g$ is continuous then, the functional equation implies that $f$ is too, and the result that $f(x) = \sin x$ follows easily.

To prove $g$ is continuous at $c$ we need to show that given an $\epsilon \gt 0$, there is a $\delta \gt 0$, such that $$|g(x) - g(c)| \lt \epsilon \quad \forall x, 0 \lt |x - c| \lt \delta$$ 

Now we have that there is some $\delta$ such that

$$ |f(x) - g(c)| \lt \frac{\epsilon}{2}, \quad \forall x, 0 \lt |x - c| \lt \delta$$

Also for any $x_1$ such that $0 \lt |x_1 - c| \lt \delta$ we have a $\delta_1$ such that $$|f(x) - g(x_1)| \lt \frac{\epsilon}{2} \quad \forall x, 0 \lt |x - x_1| \lt \delta_1 $$

Thus we can find an $x$ such that for any $0 \lt |x_1 - c| \lt \delta$ we have the above two to be true, and hence adding them gives us that

$$|g(x_1) - g(c)| \lt \epsilon \quad \forall x_1, 0 \lt |x_1 - c| \lt \delta$$

Monday, June 8, 2015

Finding a sum involving the golden ratio

This is a math oriented algorithms puzzle.

Let $\varphi$ be the golden ratio: $\dfrac{1+\sqrt{5}}{2}$.

Consider the following sum

$$S_n = [\varphi] + [2 \varphi] + \dots + [n\varphi]$$

i.e

$$ S_n = \sum_{k=1}^{n} [k \varphi]$$

where $[x]$ is the integer part of $x$.

Can you give an algorithm to compute $S_n$ that takes a polynomial in $\log n$ time?

[Solution]

Friday, June 5, 2015

Limit everywhere function

Here is a strange math problem.

Suppose $f:[0,1] \to [0,1]$ is function whose limit exists everywhere.

i.e $g(t) = \lim_{x \to t} f(x)$ is well defined, and gives rise to another function.

Now suppose $f$ and the limit function $g$ satisfy

$$ f(x) = 2g(x) - \sin x \quad \forall x \in [0,1]$$

Find all such $f$.

[Solution]

Friday, May 29, 2015

Hasty West, Lucky South.

This is a hand from bridge at Google Kirkland. I will just post the four hands and what happened (there might be interesting aspects to this hand, which I will leave you to discover on your own!)

Assume the scoring is IMPS.

IMPS
E/W 
 North
♠ QJx
♥ Axx
♦ xx
♣ T98xx
 West
♠ T98xx
♥ x
♦ Qxx
♣ AKQJ

  


 East
♠ x
♥ KT98x
♦ T98xx
♣ xx
 South
♠ AKxx
♥ QJxx
♦ AKJ
♣ xx

W N E S
1SPP3NT
allpass

West was dealer and opened 1S. After two passes South ventured a 3NT in the balancing seat and got to play there.

West quickly started off with the AKQ of clubs, on which both East and South discarded a heart (east encouraging).

At this point West shifted to a heart.

South ducked the heart to East's K and won the diamond continuation.

This was the position:

IMPS
E/W 
 North
♠ QJx
♥ Ax
♦ x
♣ T9
 West
♠ T98xx
♥ -
♦ Qx
♣ J

   


 East
♠ x
♥ T98
♦ 98xx
♣ -
 South
♠ AKxx
♥ QJ
♦ KJ
♣ -

South had lost 4 tricks and needed the rest.

Look what happened.

South cashed 4 spades throwing a club from dummy, and now the hand was

IMPS
E/W 
 North
♠ -
♥ Ax
♦ x
♣ T
 West
♠ T
♥ -
♦ Qx
♣ J

    


 East
♠ x
♥ T
♦ 98
♣ -
 South
♠ -
♥ QJ
♦ KJ
♣ -

When South played the HQ (low from dummy), west could throw a spade, but was squeezed on the heart J to the A!

South ended up making 9 tricks!

West was too hasty and didn't give the hand its due consideration. They should have paused after trick one and as the play went, after trick three.

Anyway. What would you lead? What would you do at trick two?

[btw, if you need to know who had the S7 and/or S6, I believe it was with West]

Saturday, May 23, 2015

Max area in histogram [Solution]

The problem:

Given an array $A$ of integers, $A[1], A[2], \dots, A[n]$, find a contiguous sub-array $A[i], \dots, A[j]$ such that $(j-i+1) \times \min\{A[i], \dots, A[j]\}$ is maximum.

Solution

This is a classic ACM programming contest problem.

A bunch of solutions can be found here: http://www.informatik.uni-ulm.de/acm/Locals/2003/html/judge.html

Look at Problem H.

But, the reason for this blog post was to present a different solution to this, using Cartesian Trees.

A cartesian tree for an array $A$, is a binary tree such that it is a heap formed from the elements of $A$, and the in-order traversal of the tree gives back the array in order: $A[1], A[2], \dots, A[n]$. See the diagram below (swiped from the wiki page).

 

These trees can be constructed in $O(n)$ time (see the wiki page for more details).

To solve the problem, we use divide and conquer.

First we construct a cartesian tree which gives a min-heap.

Now notice that, if $A[m]$ is the minimum element of $A$, then the optimum solution is either $n \times A[m]$, or the optimum solutions from $A[1], \dots A[m-1]$ and $A[m+1], \dots, A[n]$.

The cartesian tree of $A$ gives us $m$, and the cartesian trees for $A[1], \dots, A[m-1]$ (the left subtree) and $A[m+1], \dots, A[n]$ (the right sub-tree)!

Thus if we annotate each node $N$ of the cartesian tree with the number of nodes in that sub-tree $N_c$, we just need to compute max of $N.values \times N_c$ over all the nodes! $N.value$ is the element value from $A$.

This is an $O(n)$ time solution.

For another application of Cartesian trees, try solving this puzzle on this blog: Construct BST.

Friday, May 22, 2015

log sequence limit [Solution]

The problem was:

$x_1 \gt 0$ and $x_{n+1} = \log (1 + x_n)$.

Find $\lim_{n \to \infty} nx_n$.

Note: $x_n$ is monotonically decreasing and bounded below by $0$, and $x_n \to L = 0$ (solution of $L = \log(1+L)$).

Solution

Did you know there was something like a l'Hopital rule for sequences?

It is called the Stolz–Cesàro theorem. That can be used here, and easily gives us the limit (in fact by using the fact that $x_n \to 0$ and applying the normal l'Hopital rule twice!)

We will not use that though.

Consider the sequence $$ y_n = \dfrac{1}{x_{n+1}} = \dfrac{1}{\log(1+x_n)}$$


Now $\log (1 + x_n) = x_n - x_n^2/2 + O(x_n^3)$

Thus $$y_n = \frac{1}{x_n - x_n^2/2 + O(x_n^3)} = \frac{1}{x_n(1 - x_n/2 + O(x_n^2))}$$

$$ = \frac{1}{x_n} - \frac{1}{2} + O(x_n)$$

(Using $\dfrac{1}{1-t} = 1 + t + t^2 + \dots$).

Thus $c_n = y_n - y_{n-1} \to \dfrac{1}{2}$ (we can apply Stolz Cesaro here if we want).

Now if $a_n \to L$, then $S_n = \dfrac{a_1 + a_2 + \dots + a_n}{n} \to L$.

Thus applying the above to $c_n$, we get $\dfrac{y_n}{n} \to \dfrac{1}{2}$.

Thus $$n x_n \to 2$$

Monday, May 18, 2015

Max area in histogram

This is from some ACM programming contest, and has a bunch of good solutions, so don't search the web too quickly.

The problem is as follows:

You are given a histogram, and want to find the maximum area rectangle that can be drawn within that histogram.

Basically, given an array $A[1], A[2], \dots, A[n]$ of say integers, find a contiguous sub-array $A[i], \dots, A[j]$ such that $(j-i+1)\times \min \{A[i], \dots, A[j]\}$ is maximum.

An $O(n \log n)$ solution is acceptable, but $O(n)$ solutions exist.

[Solution]

Wednesday, May 13, 2015

log sequence limit

Consider the sequence defined as follows, with $x_1 \gt 0$.

$$x_{n+1} = \log (1 + x_n)$$

One can show that $x_n \to 0$ as $n \to \infty$ (try it).

What can you say about the sequence $y_n = nx_n$ as $n \to \infty$? Does the limit exist? If so, what is it?

Note: The $\log$ is the natural logarithm to base $e$.

[Solution]

Monday, May 11, 2015

Hopeless contract

Here is a hand from lunch bridge at Google Seattle (assume IMPs scoring, basically).

You are South, open 2S and get raised to 4S by partner.

LHO leads a low heart (singleton or 3+). This is what you see:

Lunch Bridge
E/W 
 North
♠ Kxxx
♥ AKQTx
♦ xx
♣ xx

     


 South
♠ QJTxxx
♥ Jxx
♦ xx
♣ KQ

You have 4 top losers. Is there anything you can try?

[Please think about it before reading on]






Seems like you need a defensive error.



One possibility is to play the SJ.

If you play the SJ, LHO with Ax of spades, might choose to play you for a hand like JT9xxx, xx, Axx, xx and hope for two spade tricks by playing low and partner winning the SQ.

If LHO ducks the SJ and has 3+ hearts, you can now throw a diamond on the hearts!

At the table, LHO did have Ax of spades and three hearts. Unfortunately, the declarer did not try this deceptive move, so we won't know if it would have worked at that time.

Did you think of something different? Is so, please comment!

Tuesday, May 5, 2015

Finding a non-substring [Solution]

The puzzle is here.

In brief, find shortest string which is not a substring of given string.

Solution

This will be short too.

Construct the suffix tree of given string, using say a NULL marker for non-existent branches. We can do the marking since the alphabet $\Sigma$ is known.

Now, we can find the smallest depth location where there are no branches. That location gives us a shortest string which is not a substring of the given string.

Suffix trees can be constructed and traversed in $O(n)$ time ($|\Sigma|$ is considered $O(1)$).

Saturday, May 2, 2015

Variant on Lights out [Solution]

The puzzle description is: here.

In brief: An $N\times N$ grid of lights, touching a light toggles all lights in the same row and column as that light. Give a formula for number of initial states of lights which can be all turned off.

Solution

There are two cases, when $N$ is even and $N$ is odd.

When $N$ is even, you can toggle a single light by touching all the lights in the same row and same column as that light.

Thus, any initial grid can be turned all off by targeting only the lights that are on.

So for even $N$ the formula is $2^{N^2}$ (any grid, basically).

The harder case is when $N$ is odd. There are in fact initial combinations which cannot be turned off (for e.g, the example posted in the problem blog post).

There is a nice invariant of the operation which we can use.

Suppose you treat an on light as $1$ and off as $0$.

Consider the sum over $\mathbb{F}_2$ (i.e. modulo $2$) of the numbers for each row (say $R_i$ for row $i$) and each column (say $C_j$ for column $j$). The possible values of $R_i$ and $C_j$ are $1$ and $0$ (remember: modulo $2$ or $\mathbb{F}_2$).

Then, the touching a light operation, toggles all the $R_i$ and $C_j$ at once: i.e. if $R_i$ was $1$ it becomes $0$ and vice-versa, try it out.

Thus for an initial grid to be able to be turned off, we need $R_i = C_j$ for all $i, j$, as the final grid has $R_i = C_j = 0$.

This is also a sufficient condition, and we can prove it as follows:

Proof:

Assume the grid has $R_i = C_j$ initially.

Suppose $N = 2k+1$. Then consider the $2k \times 2k$ grid formed by the topmost $2k$ rows and the leftmost $2k$ columns.

By our observation about even $N$, we can turn that grid off completely just by touching lights within that grid.

This will result in the last row and last column to have some lights on/off depending on the lights that were touched in the $2k\times 2k$ portion.

But since we started out with $R_i = C_j$ and the light touching operation does not change that, the last row and last column must all be ones, or all be zeroes. In which case the whole $(2k+1)\times (2k+1)$ grid can be turned off: if the last row and column are all ones, we just touch the bottom right light.

$\blacksquare$.

This also allows us to count: Fill in the $2k \times 2k$ grid arbitrarily. The rest of the number are forced.

Thus for odd $N = 2k+1$, the formula we are looking for is $2^{4k^2} = 2^{(N-1)^2}$.

Monday, April 27, 2015

Finding a non-substring

Suppose you are given a fixed size alphabet $\Sigma$ and a string $S$ of length $n$ over it.

The task is to find a shortest length string (formed using letters in $\Sigma$) which is *not* a substring of $S$.

Any shorter string will be a substring of $S$.

For example, if $\Sigma = \{0, 1\}$ and $S = 01100$, then a shortest length string will be of length $3$ (for e.g: $000$ will do).

Can you do it in $O(n)$ time?

[Solution]

Saturday, April 25, 2015

Variant on Lights Out

This is similar to the Lights Out game, and is actually based on a problem from an old Bay Area Maths Olympiad I had seen.

You have an $N \times N$ grid of lights, each light is either on or off (different lights could be in different states).

When you touch a light, all the lights in the same row and same column as that light toggle, i.e. if they were on, they turn off and vice-versa.

For example, say the grid was

$$\begin{bmatrix} \blacksquare & \blacksquare & \Box\\\Box & \Box & \Box\\ \Box & \blacksquare & \Box \end{bmatrix}$$

Now if you touch the light in the top left corner, it becomes

$$\begin{bmatrix} \Box & \Box & \blacksquare \\ \blacksquare & \Box & \Box \\ \blacksquare & \blacksquare & \Box \end{bmatrix}$$



The goal of the lights out puzzle is usually to turn all the lights off by some sequence of touches, given a starting grid.

This problem is slightly different.

Given an $N$, you need to give a formula for exactly how many grids can be converted to all off by some sequence of touches. The already all off grid should also be counted.

[Note: Rotations of the same grid etc are considered to be different, so there are a total of $2^{N^2}$ grids.]

[Solution]




Friday, April 24, 2015

A good slam.

This is a hand I had posted to bridgebase forums a long time back, as a play problem for intermediate players.

You are South, playing IMPS/Rubber and reach 6H.

How will you play on a club lead?

IMPS
None 
 North
♠ AKJT3
♥ AQJ
♦ AJ2
♣ A5



   




 South
♠ 62
♥ K6542
♦ KT843
♣ 3


[I will post the suggested line in a few days. Please feel free to comment.]

Suggested line (Posted July 23rd 2015, sorry, had forgotten about this)


When I posted this problem to bridge base forums, I had included the information that you win the CA, play AQ of trumps, RHO showing out. I missed that when posting on the blog.

In that scenario, the suggested line was to run the DJ. Now I am not so sure if this is a good problem for intermediate players.

Sunday, April 19, 2015

Integer part of $(1 + \sqrt{2})^n$ [Solution]

The algorithm puzzle was to find the integer part of $(1 + \sqrt{2})^n$ using only integer arithmetic, in number of operations which is polynomial in $\log n$

[Note: the puzzle post mistakenly said time, instead of number of operations. Fixed now]

Solution

By the binomial theorem, notice that

$$ (1 + \sqrt{2})^n = a_n + b_n \sqrt{2}$$

where $a_n$ and $b_n$ are both integers.

Now

$$(a_n + b_n \sqrt{2})(1 + \sqrt{2}) = (a_n + 2b_n) + (a_n +b_n)\sqrt{2}$$

Thus we get the recurrence relations:

$$ a_{n+1} = a_n + 2b_n $$
$$ b_{n+1} = a_n + b_n $$

This can be written in matrix form as

$$\begin{bmatrix}1&2\\1&1\end{bmatrix}\begin{bmatrix} a_n\\b_n \end{bmatrix} = \begin{bmatrix}a_{n+1}\\b_{n+1} \end{bmatrix}$$

i.e.
$$A \begin{bmatrix}a_n\\b_n \end{bmatrix} = \begin{bmatrix}a_{n+1}\\b_{n+1} \end{bmatrix}$$

Giving us

$$ A^n \begin{bmatrix}a_1\\b_1 \end{bmatrix} = \begin{bmatrix}a_{n+1}\\b_{n+1} \end{bmatrix}$$

$A^n$ can be computed in $O(\log n)$ integer operations.

Once we have $(a_n, b_n)$ we can compute the integer part of $a_n + b_n \sqrt{2}$ by computing the integer part of $b_n \sqrt{2}$ using binary search for integer $x$ such that $x^2 \lt 2b_n^2 \lt (x+1)^2$ (or other algorithms) and adding that to $a_n$.

We could also solve this problem by a more straight-forward divide and conquer + memoization algorithm, like we did for Fibonacci earlier, by writing $(a_{2n}, b_{2n})$ in terms of $(a_n, b_n)$ etc.

Thursday, April 16, 2015

Ramaiah entrance test question [Solution]

The problem was to show that  the sequence of numbers

$$49, 4489, 444889, \dots $$

where each number is formed by inserting 48 in the middle of the previous number:

$$49 \to 4\underline{48}9 \to 44\underline{48}89 \to \dots$$

has only perfect squares!

Solution


Any number is of the form $n$ 4s followed by $n-1$ 8s followed by 9.

This can be rewritten as the sum of

$4444\dots44$ (a $2n$ digit number) 

$44\dots4$  (an $n$ digit number)

1

This is basically

$$\frac{4(10^{2n}-1)}{9} + \frac{4(10^{n}-1)}{9}  + 1 $$

$$= \left(\frac{2\times10^n + 1}{3}\right)^2$$

Tuesday, April 14, 2015

Integer part of $(1 + \sqrt{2})^n$

Give an algorithm to compute the integer part of

$$(1+ \sqrt{2})^n $$

in number of operations which is polynomial in $\log n$.

Note: I had a mistake earlier by using time, instead of number of operations. Even though we use only polynomial in $\log n$ integer operations, the running time will be $\Omega(n)$, as we are dealing with $\theta(n)$ bit integers.

[Solution]

Friday, April 10, 2015

A question from Ramaiah entrance test

Ramaiah's classes were (are) popular coaching classes for IIT JEE exam preparation in Hyderabad. They themselves had an entrance exam!

These Ramaiah entrance tests contained some very nice problems.

This was a question I first saw on a Ramaiah entrance test when my brother appeared for it (1990). The question is actually much older than that, probably the 1800s.

Anyway, here goes:

Consider the sequence of numbers

$$49, 4489, 444889, \dots $$

Each number is formed by inserting 48 in the middle of the previous number.

$$49 \to 4\underline{48}9 \to 44\underline{48}89 \to \dots$$

Show that all these numbers are perfect squares!

[Solution]

Wednesday, April 8, 2015

Another textbook hand.

This hand is based on one that occurred in a pairs game at a recent Sectional in Everett, WA.

Assume you are playing teams, though.

You are South and reach 6H, and get a club lead.

IMPS
None 
 North
♠ AQT432
♥ 72
♦ A2
♣ KQ2

  


 South
♠ 5
♥ AKJT986
♦ 43
♣ A43

How will you play?


Suggested line (added April 16 2015)

If trumps are 2-2, you will have an easy 12 tricks.

If you have a trump loser, then you need to do something about the diamond loser.

Spades are a potential source of that trick.

Since you might need entries to dummy, you win trick one in hand.

If spades are 4-2, you need 3 entries in the non-spade suits to setup and cash the extra spade tricks (the SA is an entry for a ruff).

If spades are 5-1, you need 4 non-spade entries. Not sure what to do about a 6-0 spade break.

So the suggested line is:

Win CA in hand. Play spade to A and ruff a spade in hand with one of J,T,9,8. Preserve the 6!

If spades are 4-2, you can now just play trumps from the top.

If spades are 5-1, and LHO hasn't ruffed, you now play the HJ from hand! The opponents cannot duck this (if trumps are 3-1) and now the H7 is the extra entry you need to dummy!

Tuesday, April 7, 2015

Generate a random heap [Solution]

The puzzle was here.

Solution

I will be brief.

For O(n) random number calls, the idea is to grow the heap top down.

n has to be the topmost element. Now n-1 could be any of its two children. Pick a spot for that, randomly.

Now there are 3 new spots available for n-2. Pick one of those three randomly.

This leads to 4 new spots for n-3 and so on.

At the end, you have a random heap.

For an O(1) random number calls algorithm, try proving that there are exactly n! (i.e. factorial of n) heaps, and provide a way to encode/decode a heap given a random number from 1 to n!.

Sunday, April 5, 2015

Integration problem [Solution]

The puzzle was to compute

$$ \int \frac{1+x^2}{(1-x^2)\sqrt{1+x^4}} dx$$

Solution

As usual, a clever substitution needs to be sought.

In this case, you divide the numerator and denominator by $x^2$ and then make the substitution $t = x - \frac{1}{x}$.

This results in

$$ -\int \frac{dt}{t\sqrt{t^2+1}}$$

which is a standard integral.

Thursday, April 2, 2015

Rabbit plays A diamond

[Like the previous Rabbit stories, this is based on the Menagerie characters. This was also posted on bridgewinners.]


Karapet was hoping he would cut the Rabbit, but as usual, the Rabbit with his darn luck got paired with the Hog.

"Again? Anyway, how bad can it be? At least it is Secretary Bird and not Papa. It can't be worse than yesterday when...".

Karapet's thoughts were interrupted by the Hog loudly ordering some jam sandwiches.

The Rabbit was the dealer and dealt himself ♠AK ♥KQT9876 ♦A32 ♣A.

He opened 1♥, Secretary Bird, who was on his left passed. Hog surprised everyone by passing, and Karapet doubled.

Just then the waiter arrived with the sandwiches and the Hog offered him some. Saying "No thanks", the Rabbit passed (the sandwich no bid, if I may).

The Bird bid 2♣ , Hog passed (again!), and Karapet bid 2♦.

The Rabbit now thought, "With my diamond honour over Karapet's, my hand has improved. I was going to invite, but I think I should bid game now". His nose quivering with excitement, the Rabbit bid 4♥ with shaking hands.

The Bird, Hog and Karapet passed. The Rabbit passed out of habit. "No double this time Rabbit", chuckled Hog.

The Bird led the ♦T.

The Hog placed the dummy down awkwardly, as he took the Rabbit's cards for a look see. "Wonderfully bid Rabbit. Now you just have to make it", said Hog, while scraping the last globs of jam on the plate with his finger.

These were the cards

Rubber
None 
 Hog
♠ 5432
♥ 32
♦ 5432
♣ 432








 Rabbit
♠ AK
♥ KQT9876
♦ A76
♣ A


W N E S



1H
PPXP*
2CP2D4H
PPP


Rabbit immediately called for a low ♦ and Karapet overtook the ♦T with the ♦K.

Now the Rabbit began to think. "What was it? Count your losers? Lose two diamonds and the ♥A. Maybe I should duck the diamond? Or was the rule to win it?".

Then inspiration struck him, "Aces are meant to take Kings!". The decision was easy. He needed to win it and then drive out the ♥A.

So he reached for the ♦A and plunked it on the table. To his dismay, he noticed a card lying beneath the ♦A. He was surprised to see that it was the ♥T.

"What? How? I sorted my cards. Wait there is something on back of
A. It is some ja...".

"You never could tell the difference between a heart and a diamond", interrupted the Hog.

"It is a played card. Since you won the trick, you need to lead that to the next trick. Those are our rules", said the Bird.

"What? No. It is not my fault. It is those damn sandwi...".

"In fact I would not be surprised if you didn't notice that you had a club in with your diamonds too", interrupted the Hog again.

Inspite of the Rabbit's protests, he was forced to play the ♥T to the next trick.

These were the four hands

Rubber
None 
 Hog
♠ 5432
♥ 32
♦ 5432
♣ 432
 Bird
♠ T98
♥ J54
♦ T
♣ JT8765




 Karapet
♠ QJ76
♥ A
♦ KQJ98
♣ KQ9
 Rabbit
♠ AK
♥ KQT9876
♦ A76
♣ A

W N E S
1H
PPXP*
2CP2D4H
PPP


The Bird quickly played the ♥J to get the cheap trick that he had directed himself to.

Poor Karapet had to overtake with his bare Ace. He could cash two more diamonds, but even Rabbit could take the rest.

"Just my luck, as usual. Rabbit had to have a heart in with the ♦, and you had to play the ♥J. If you play low, I can win and promote your Jack for the setting trick!"

"Jam sandwiches, anyone? I am ordering more", said the Hog, licking his fingers.

[You guessed it. It was the Hog who had stuck the cards together with jam, and the Rabbit had in fact sorted his cards correctly.]