In backtracking what decides if the next recursive call should move sequentially to the next position/ jump ahead based on the element just processed?

1 day ago 1
ARTICLE AD BOX

The difference comes down to what the recursive parameter actually represents in each problem.

In permutations, ind is a position slot you're filling

Think of it as: "which seat am I currently assigning someone to?"

The loop for i = ind to n-1 asks: which element should go into seat ind? You try every remaining element by swapping it into position ind, then recurse with ind+1 ,  meaning "seat ind is filled, now fill seat ind+1.

You always recurse with ind+1 regardless of i, because i is just the candidate you're trying for the current seat. After the swap, position ind is decided, move to the next seat.

Using i+1 here would be wrong. It would mean "skip all seats up to i", losing positions entirely.

In partitioning, ind is where your next cut must start

Think of it as: "I've committed to everything before ind, now partition the rest."

The loop for i = ind to n-1 asks: where should the current partition end? When you find a valid palindrome from ind to i, you recurse with i+1 , meaning "this chunk is consumed up through i, continue from i+1."

Using ind+1 here would be wrong. It would force every partition to be exactly one character long, ignoring multi-character palindromes like "aba".

The core difference

PermutationsPartitioningParameter meanswhich position to fill nextwhere the next element startsLoop variable i meanswhich element to place at indwhere to end the current chunkRecurse withind+1 (next position)i+1 (next unprocessed element)ind advances byalways exactly 1a variable amount (chunk size)

A useful mental test: ask yourself "after this recursive call, what has been decided?" In permutations, one position has been decided, so you advance the position counter by 1. In partitioning, a variable-length chunk has been consumed, so you advance past wherever that chunk ended, which is i, not ind.

This same pattern (i+1 vs fixed increment) appears in subsets, combination sum, and word break for the same reason: any time you're consuming variable-length pieces of input rather than filling fixed slots, the next call starts after whatever you just consumed.

Read Entire Article