Ride-hailing app~25 min2s · 256 MBtarget O(number of valid orders × n) time, O(n) spaceclassic twin: lc-47backtracking
A ride-hailing driver has a list of waiting riders, and each rider is in one of four fare zones, numbered 0 to 3. Riders from the same zone are interchangeable for the driver.
To avoid blocking one street, the driver never picks up two riders from the same zone one after the other. The driver collects every rider once.
You count the different orders of zones the driver can follow.
Write count_pickup_orders(zones).
zones[i] is the zone number of waiting rider i, from 0 to 3.Input: zones = [0,0,1,1,2]
Output: 12The solution counts the riders waiting in each zone, then fills the positions one at a time. At each position it tries every zone that still has riders and differs from the last pickup.
| First zone | Valid orders that start with it |
|---|---|
| 0 | 5, for example 0,1,0,1,2 and 0,2,1,0,1 |
| 1 | 5, for example 1,0,1,0,2 and 1,2,0,1,0 |
| 2 | 2, namely 2,0,1,0,1 and 2,1,0,1,0 |
There are 12 different valid orders in all. Without the rule, the same riders have 30 different orders.
Input: zones = [0,0,0,1]
Output: 0Three pickups from zone 0 need at least two riders from other zones between them. There is only one, so no order is valid.
Input: zones = [3]
Output: 1There is a single order, 3, and it has no neighbours to compare.
1 ≤ len(zones) ≤ 12zones[i] is 0, 1, 2 or 3Twelve riders have 12 factorial orders, which is 479,001,600. Many of them repeat the same list of zones, because equal zones are interchangeable. The search picks a zone instead of a rider, so each distinct order is built once, and it never builds an order past two equal neighbours.