VOOZH about

URL: https://www.geeksforgeeks.org/dsa/nuts-bolts-problem-lock-key-problem-using-quick-sort/

⇱ Nuts & Bolts (or Lock & Key) Problem - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Nuts & Bolts (or Lock & Key) Problem

Last Updated : 7 Apr, 2026

Given a set of n nuts of different sizes and n bolts of different sizes. There is a one-one mapping between nuts and bolts. Match nuts and bolts efficiently. Comparison of a nut to another nut or a bolt to another bolt is not allowed. The elements in output should follow the following order: { !,#,$,%,&,*,?,@,^ }

Input: , nuts[] = {@, %, $, #, ^}, bolts[] = {%, @, #, $ ^}
Output: # $ % @ ^

Explanation: As per the order # should come first after that $ then % then @ and ^.

Input: nuts[] = {^, &, %, @, #, *, $, ?, !}, bolts[] = {?, #, @, %, &, *, $ ,^, !}
Output: ! # $ % & * ? @ ^

Explanation: We'll have to match first ! then # , $, %, &, *, @, ^, ? as per the required ordering.

Quick sort is applied on nuts and bolts simultaneously — the last bolt acts as a pivot to partition nuts, then the matched nut partitions bolts. This cross-partitioning repeats recursively on left and right sub-arrays until all pairs are matched.

Here how it works:

1. Pick the last element of bolts[] as pivot and partition the nuts[] array around it, returning index i.
2. Use nuts[i] as the next pivot to partition the bolts[] array. Each partition runs in O(n).
3. Recur on the left and right sub-arrays of both nuts[] and bolts[] until all pairs are matched.


Output
Matched nuts and bolts are : 
 # $ % & @ ^

Why we cannot use Hashing to solve this ?

If we use hashing, then we will have to compare nuts with nuts or bolts with bolts either while inserting into the hash and/or while printing the result in sorted order.


Comment